diff --git a/.gitignore b/.gitignore index 63873b949..ccdad3ade 100644 --- a/.gitignore +++ b/.gitignore @@ -55,3 +55,7 @@ xcuserdata /Linux/ /Telegram/Makefile *.*~ + +_build_ +_conan_build_ + diff --git a/.gitmodules b/.gitmodules index 288741058..e69de29bb 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,12 +0,0 @@ -[submodule "Telegram/ThirdParty/libtgvoip"] - path = Telegram/ThirdParty/libtgvoip - url = https://github.com/telegramdesktop/libtgvoip -[submodule "Telegram/ThirdParty/variant"] - path = Telegram/ThirdParty/variant - url = https://github.com/mapbox/variant -[submodule "Telegram/ThirdParty/GSL"] - path = Telegram/ThirdParty/GSL - url = https://github.com/Microsoft/GSL.git -[submodule "Telegram/ThirdParty/Catch"] - path = Telegram/ThirdParty/Catch - url = https://github.com/philsquared/Catch diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..b314a15fe --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,42 @@ +cmake_minimum_required(VERSION 3.10) +project(telegram-desktop) + +if(EXISTS ${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) + include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) + conan_basic_setup() +else() + find_package(OpenSSL REQUIRED) +endif() + +set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cotire/CMake;${PROJECT_SOURCE_DIR}/modules/") +include(cotire) + +set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD_REQUIRED YES) +set(CMAKE_CXX_EXTENSIONS OFF) + +set(CMAKE_AUTOMOC ON) +set(CMAKE_INCLUDE_CURRENT_DIR ON) +# Ignore automoc-ing generated files (@tbd?) +cmake_policy(SET CMP0071 OLD) + +# Needs OpenAL-SOFT +# Install via `brew install openal-soft` and configure with `env OPENALDIR=/usr/local/opt/openal-soft` +find_package(OpenAL REQUIRED) +find_package(FFmpeg REQUIRED) +find_package(Zlib REQUIRED) +#@todo Turn into find_package(Opus REQUIRED) +find_library(OPUS_LIB opus) +find_path(OPUS_INCLUDE_DIR opus/opus.h) + +if (NOT SWSCALE_FOUND) + message(FATAL_ERROR "FFmpeg swscale is required") +endif() +if (NOT SWRESAMPLE_FOUND) + message(FATAL_ERROR "FFmpeg swresample is required") +endif() +if (NOT OPUS_LIB) + message(FATAL_ERROR "opus codec is required") +endif() + +add_subdirectory(Telegram) diff --git a/README.md b/README.md index 683bea0a9..d4c3909d0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,14 @@ -# [Telegram Desktop][telegram_desktop] – Official Messenger +# [Telegram Desktop][telegram_desktop] - pro.cxx fork -This is the complete source code and the build instructions for the alpha version of the official desktop client for the [Telegram][telegram] messenger, based on the [Telegram API][telegram_api] and the [MTProto][telegram_proto] secure protocol. +This is the complete source code and the build instructions for the alpha version of the pro.cxx fork of desktop client for the [Telegram][telegram] messenger, based on the [Telegram API][telegram_api] and the [MTProto][telegram_proto] secure protocol. + +## Build instructions + + mkdir _build_ + cd _build_ + conan install .. --build missing + cmake -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_PREFIX_PATH=/usr/local/opt/qt5/ .. + ninja [![Version](https://badge.fury.io/gh/telegramdesktop%2Ftdesktop.svg)](https://github.com/telegramdesktop/tdesktop/releases) [![Build Status](https://travis-ci.org/telegramdesktop/tdesktop.svg?branch=dev)](https://travis-ci.org/telegramdesktop/tdesktop) @@ -28,7 +36,6 @@ The source code is published under GPLv3 with OpenSSL exception, the license is * liblzma ([public domain](http://tukaani.org/xz/)) * Google Breakpad ([License](https://chromium.googlesource.com/breakpad/breakpad/+/master/LICENSE)) * Google Crashpad ([Apache License 2.0](https://chromium.googlesource.com/crashpad/crashpad/+/master/LICENSE)) -* GYP ([BSD License](https://github.com/bnoordhuis/gyp/blob/master/LICENSE)) * Ninja ([Apache License 2.0](https://github.com/ninja-build/ninja/blob/master/COPYING)) * OpenAL Soft ([LGPL](http://kcat.strangesoft.net/openal.html)) * Opus codec ([BSD License](http://www.opus-codec.org/license/)) @@ -39,10 +46,6 @@ The source code is published under GPLv3 with OpenSSL exception, the license is * Emoji alpha codes ([MIT License](https://github.com/emojione/emojione/blob/master/extras/alpha-codes/LICENSE.md)) * Catch test framework ([Boost License](https://github.com/philsquared/Catch/blob/master/LICENSE.txt)) -## Build instructions - -* [Visual Studio 2017][msvc] -* [Xcode 8][xcode] * [GYP/CMake on GNU/Linux][cmake] [//]: # (LINKS) diff --git a/Telegram/CMakeLists.txt b/Telegram/CMakeLists.txt new file mode 100644 index 000000000..a49e8f812 --- /dev/null +++ b/Telegram/CMakeLists.txt @@ -0,0 +1,671 @@ +find_package(Qt5 COMPONENTS Core Gui Widgets Network REQUIRED) + + +# defines +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + if (CMAKE_SIZEOF_VOID_P EQUAL 8) + add_definitions(-DQ_OS_LINUX64) + else() + add_definitions(-DQ_OS_LINUX32) + endif() +endif() + +find_program(CCACHE ccache) +if (CCACHE) + message(STATUS "Enabling ccache") + set(CMAKE_C_COMPILER_LAUNCHER ${CCACHE}) + set(CMAKE_CXX_COMPILER_LAUNCHER ${CCACHE}) +endif() + +##====================== +## Codegen Tools +##====================== + +include_directories(SourceFiles) +add_subdirectory(SourceFiles/codegen) + +#-w<(PRODUCT_DIR)/../.. -- wtf is that +add_custom_command( + COMMENT "Generating palette" + OUTPUT + styles/palette.h + styles/palette.cpp + COMMAND + codegen_style -I${CMAKE_CURRENT_SOURCE_DIR}/Resources -I${CMAKE_CURRENT_SOURCE_DIR} + -o${CMAKE_CURRENT_BINARY_DIR}/styles -w${CMAKE_SOURCE_DIR} + colors.palette + WORKING_DIRECTORY styles + DEPENDS + codegen_style + ${CMAKE_CURRENT_SOURCE_DIR}/Resources/colors.palette + MAIN_DEPENDENCY ${CMAKE_CURRENT_SOURCE_DIR}/Resources/colors.palette +) +add_custom_target(palette_output + DEPENDS styles/palette.h styles/palette.cpp) + +add_custom_command( + COMMENT "Generating numbers" + OUTPUT + numbers.h + numbers.cpp + COMMAND + codegen_numbers -o${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/Resources/numbers.txt + WORKING_DIRECTORY . + DEPENDS + codegen_numbers + ${CMAKE_CURRENT_SOURCE_DIR}/Resources/numbers.txt + MAIN_DEPENDENCY ${CMAKE_CURRENT_SOURCE_DIR}/Resources/numbers.txt +) +add_custom_target(numbers_output + DEPENDS numbers.h numbers.cpp) + +add_custom_command( + COMMENT "Generating langs" + OUTPUT + lang_auto.h + lang_auto.cpp + COMMAND + codegen_lang -o${CMAKE_CURRENT_BINARY_DIR} -w${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/Resources/langs/lang.strings + WORKING_DIRECTORY . + DEPENDS + codegen_lang + ${CMAKE_CURRENT_SOURCE_DIR}/Resources/langs/lang.strings + MAIN_DEPENDENCY ${CMAKE_CURRENT_SOURCE_DIR}/Resources/langs/lang.strings +) +add_custom_target(lang_output + DEPENDS lang_auto.h lang_auto.cpp) + +add_custom_command( + COMMENT "Generating emoji" + OUTPUT + emoji.cpp + emoji.h + emoji_suggestions_data.cpp + emoji_suggestions_data.h + COMMAND + codegen_emoji ${CMAKE_CURRENT_SOURCE_DIR}/Resources/emoji_autocomplete.json -o ${CMAKE_CURRENT_BINARY_DIR} + WORKING_DIRECTORY . + DEPENDS + codegen_emoji + ${CMAKE_CURRENT_SOURCE_DIR}/Resources/emoji_autocomplete.json + VERBATIM +) +add_custom_target(emoji_output + DEPENDS + emoji.h + emoji.cpp + emoji_suggestions_data.cpp + emoji_suggestions_data.h +) + +add_custom_command( + COMMENT "Generating scheme" + OUTPUT + scheme.cpp + scheme.h + COMMAND + python ${CMAKE_CURRENT_SOURCE_DIR}/SourceFiles/codegen/scheme/codegen_scheme.py -o${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/Resources/scheme.tl + WORKING_DIRECTORY . + DEPENDS + ${CMAKE_CURRENT_SOURCE_DIR}/SourceFiles/codegen/scheme/codegen_scheme.py + ${CMAKE_CURRENT_SOURCE_DIR}/Resources/scheme.tl + MAIN_DEPENDENCY ${CMAKE_CURRENT_SOURCE_DIR}/Resources/scheme.tl + VERBATIM +) +add_custom_target(scheme_output + DEPENDS scheme.h scheme.cpp) + +##======== + +list(APPEND style_files + Resources/basic + SourceFiles/boxes/boxes + SourceFiles/calls/calls + SourceFiles/chat_helpers/chat_helpers + SourceFiles/dialogs/dialogs + SourceFiles/history/history + SourceFiles/intro/intro + SourceFiles/media/player/media_player + SourceFiles/media/view/mediaview + SourceFiles/overview/overview + SourceFiles/profile/profile + SourceFiles/settings/settings + SourceFiles/ui/widgets/widgets + SourceFiles/window/window +) + +foreach (src ${style_files}) +# '-w<(PRODUCT_DIR)/../..', + get_filename_component(src_file ${src} NAME) + add_custom_command( + COMMENT "Generating ${src_file}" + OUTPUT + ${CMAKE_CURRENT_BINARY_DIR}/styles/style_${src_file}.h + ${CMAKE_CURRENT_BINARY_DIR}/styles/style_${src_file}.cpp + COMMAND + codegen_style -I${CMAKE_CURRENT_SOURCE_DIR}/Resources -I${CMAKE_CURRENT_SOURCE_DIR} + -I${CMAKE_CURRENT_SOURCE_DIR}/SourceFiles + -o${CMAKE_CURRENT_BINARY_DIR}/styles -w${CMAKE_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/${src}.style + DEPENDS + codegen_style + ${CMAKE_CURRENT_SOURCE_DIR}/${src}.style + MAIN_DEPENDENCY ${CMAKE_CURRENT_SOURCE_DIR}/${src}.style + ) + add_custom_target(${src_file}_styles_output + DEPENDS + ${CMAKE_CURRENT_BINARY_DIR}/styles/style_${src_file}.h + ${CMAKE_CURRENT_BINARY_DIR}/styles/style_${src_file}.cpp + ) + + list(APPEND style_sources + ${CMAKE_CURRENT_BINARY_DIR}/styles/style_${src_file}.cpp) + +endforeach() + +##====================== +## Main app +##====================== + +#add_subdirectory(SourceFiles/boxes) - see comment in that dir + +set(APP_SRC + ${CMAKE_CURRENT_BINARY_DIR}/styles/palette.cpp + ${CMAKE_CURRENT_BINARY_DIR}/numbers.cpp + ${CMAKE_CURRENT_BINARY_DIR}/lang_auto.cpp + ${CMAKE_CURRENT_BINARY_DIR}/scheme.cpp + ${CMAKE_CURRENT_BINARY_DIR}/emoji.cpp + ${CMAKE_CURRENT_BINARY_DIR}/emoji_suggestions_data.cpp + ${style_sources} + + SourceFiles/base/observer.cpp + SourceFiles/base/parse_helper.cpp + SourceFiles/base/qthelp_url.cpp + SourceFiles/base/runtime_composer.cpp + SourceFiles/base/task_queue.cpp + SourceFiles/base/timer.cpp + + SourceFiles/boxes/about_box.cpp + SourceFiles/boxes/abstract_box.cpp + SourceFiles/boxes/add_contact_box.cpp + SourceFiles/boxes/autolock_box.cpp + SourceFiles/boxes/background_box.cpp + SourceFiles/boxes/calendar_box.cpp + SourceFiles/boxes/change_phone_box.cpp + SourceFiles/boxes/confirm_box.cpp + SourceFiles/boxes/confirm_phone_box.cpp + SourceFiles/boxes/connection_box.cpp + SourceFiles/boxes/download_path_box.cpp + SourceFiles/boxes/edit_color_box.cpp + SourceFiles/boxes/edit_participant_box.cpp + SourceFiles/boxes/edit_privacy_box.cpp + SourceFiles/boxes/language_box.cpp + SourceFiles/boxes/local_storage_box.cpp + SourceFiles/boxes/mute_settings_box.cpp + SourceFiles/boxes/notifications_box.cpp + SourceFiles/boxes/passcode_box.cpp + SourceFiles/boxes/peer_list_box.cpp + SourceFiles/boxes/peer_list_controllers.cpp + SourceFiles/boxes/photo_crop_box.cpp + SourceFiles/boxes/rate_call_box.cpp + SourceFiles/boxes/report_box.cpp + SourceFiles/boxes/self_destruction_box.cpp + SourceFiles/boxes/send_files_box.cpp + SourceFiles/boxes/sessions_box.cpp + SourceFiles/boxes/share_box.cpp + SourceFiles/boxes/sticker_set_box.cpp + SourceFiles/boxes/stickers_box.cpp + SourceFiles/boxes/username_box.cpp + + SourceFiles/calls/calls_box_controller.cpp + SourceFiles/calls/calls_call.cpp + SourceFiles/calls/calls_emoji_fingerprint.cpp + SourceFiles/calls/calls_instance.cpp + SourceFiles/calls/calls_panel.cpp + SourceFiles/calls/calls_top_bar.cpp + + SourceFiles/chat_helpers/bot_keyboard.cpp + SourceFiles/chat_helpers/emoji_list_widget.cpp + SourceFiles/chat_helpers/emoji_suggestions_widget.cpp + SourceFiles/chat_helpers/field_autocomplete.cpp + SourceFiles/chat_helpers/gifs_list_widget.cpp + SourceFiles/chat_helpers/message_field.cpp + SourceFiles/chat_helpers/stickers.cpp + SourceFiles/chat_helpers/stickers_list_widget.cpp + SourceFiles/chat_helpers/tabbed_panel.cpp + SourceFiles/chat_helpers/tabbed_section.cpp + SourceFiles/chat_helpers/tabbed_selector.cpp + + SourceFiles/core/click_handler.cpp + SourceFiles/core/click_handler_types.cpp + SourceFiles/core/file_utilities.cpp + SourceFiles/core/single_timer.cpp + SourceFiles/core/utils.cpp + + SourceFiles/data/data_abstract_structure.cpp + SourceFiles/data/data_drafts.cpp + + SourceFiles/dialogs/dialogs_indexed_list.cpp + SourceFiles/dialogs/dialogs_inner_widget.cpp + SourceFiles/dialogs/dialogs_layout.cpp + SourceFiles/dialogs/dialogs_list.cpp + SourceFiles/dialogs/dialogs_row.cpp + SourceFiles/dialogs/dialogs_search_from_controllers.cpp + SourceFiles/dialogs/dialogs_widget.cpp + + SourceFiles/history/history.cpp + SourceFiles/history/history_admin_log_filter.cpp + SourceFiles/history/history_admin_log_inner.cpp + SourceFiles/history/history_admin_log_item.cpp + SourceFiles/history/history_admin_log_section.cpp + SourceFiles/history/history_drag_area.cpp + SourceFiles/history/history_inner_widget.cpp + SourceFiles/history/history_item.cpp + SourceFiles/history/history_location_manager.cpp + SourceFiles/history/history_media_types.cpp + SourceFiles/history/history_message.cpp + SourceFiles/history/history_service.cpp + SourceFiles/history/history_service_layout.cpp + SourceFiles/history/history_widget.cpp + + SourceFiles/inline_bots/inline_bot_layout_internal.cpp + SourceFiles/inline_bots/inline_bot_layout_item.cpp + SourceFiles/inline_bots/inline_bot_result.cpp + SourceFiles/inline_bots/inline_bot_send_data.cpp + SourceFiles/inline_bots/inline_results_widget.cpp + + SourceFiles/intro/introcode.cpp + SourceFiles/intro/introphone.cpp + SourceFiles/intro/intropwdcheck.cpp + SourceFiles/intro/introsignup.cpp + SourceFiles/intro/introstart.cpp + SourceFiles/intro/introwidget.cpp + + SourceFiles/lang/lang_cloud_manager.cpp + SourceFiles/lang/lang_file_parser.cpp + SourceFiles/lang/lang_instance.cpp + SourceFiles/lang/lang_keys.cpp + SourceFiles/lang/lang_tag.cpp + SourceFiles/lang/lang_translator.cpp + + SourceFiles/media/player/media_player_button.cpp + SourceFiles/media/player/media_player_cover.cpp + SourceFiles/media/player/media_player_float.cpp + SourceFiles/media/player/media_player_instance.cpp + SourceFiles/media/player/media_player_list.cpp + SourceFiles/media/player/media_player_panel.cpp + SourceFiles/media/player/media_player_volume_controller.cpp + SourceFiles/media/player/media_player_widget.cpp + + SourceFiles/media/view/media_clip_controller.cpp + SourceFiles/media/view/media_clip_playback.cpp + SourceFiles/media/view/media_clip_volume_controller.cpp + + SourceFiles/media/media_audio.cpp + SourceFiles/media/media_audio_capture.cpp + SourceFiles/media/media_audio_ffmpeg_loader.cpp + SourceFiles/media/media_audio_loader.cpp + SourceFiles/media/media_audio_loaders.cpp + SourceFiles/media/media_audio_track.cpp + SourceFiles/media/media_child_ffmpeg_loader.cpp + SourceFiles/media/media_clip_ffmpeg.cpp + SourceFiles/media/media_clip_implementation.cpp + SourceFiles/media/media_clip_qtgif.cpp + SourceFiles/media/media_clip_reader.cpp + + SourceFiles/mtproto/auth_key.cpp + SourceFiles/mtproto/config_loader.cpp + SourceFiles/mtproto/connection.cpp + SourceFiles/mtproto/connection_abstract.cpp + SourceFiles/mtproto/connection_auto.cpp + SourceFiles/mtproto/connection_http.cpp + SourceFiles/mtproto/connection_tcp.cpp + SourceFiles/mtproto/core_types.cpp + SourceFiles/mtproto/dc_options.cpp + SourceFiles/mtproto/dcenter.cpp + SourceFiles/mtproto/facade.cpp + SourceFiles/mtproto/mtp_instance.cpp + SourceFiles/mtproto/rpc_sender.cpp + SourceFiles/mtproto/rsa_public_key.cpp + SourceFiles/mtproto/session.cpp + SourceFiles/mtproto/special_config_request.cpp + SourceFiles/mtproto/type_utils.cpp + + SourceFiles/overview/overview_layout.cpp + + SourceFiles/profile/profile_back_button.cpp + SourceFiles/profile/profile_block_actions.cpp + SourceFiles/profile/profile_block_channel_members.cpp + SourceFiles/profile/profile_block_group_members.cpp + SourceFiles/profile/profile_block_info.cpp + SourceFiles/profile/profile_block_invite_link.cpp + SourceFiles/profile/profile_block_peer_list.cpp + SourceFiles/profile/profile_block_settings.cpp + SourceFiles/profile/profile_block_shared_media.cpp + SourceFiles/profile/profile_block_widget.cpp + SourceFiles/profile/profile_channel_controllers.cpp + SourceFiles/profile/profile_common_groups_section.cpp + SourceFiles/profile/profile_cover.cpp + SourceFiles/profile/profile_cover_drop_area.cpp + SourceFiles/profile/profile_fixed_bar.cpp + SourceFiles/profile/profile_inner_widget.cpp + SourceFiles/profile/profile_section_memento.cpp + SourceFiles/profile/profile_userpic_button.cpp + SourceFiles/profile/profile_widget.cpp + + SourceFiles/settings/settings_advanced_widget.cpp + SourceFiles/settings/settings_background_widget.cpp + SourceFiles/settings/settings_block_widget.cpp + SourceFiles/settings/settings_chat_settings_widget.cpp + SourceFiles/settings/settings_cover.cpp + SourceFiles/settings/settings_fixed_bar.cpp + SourceFiles/settings/settings_general_widget.cpp + SourceFiles/settings/settings_info_widget.cpp + SourceFiles/settings/settings_inner_widget.cpp + SourceFiles/settings/settings_layer.cpp + SourceFiles/settings/settings_notifications_widget.cpp + SourceFiles/settings/settings_privacy_controllers.cpp + SourceFiles/settings/settings_privacy_widget.cpp + SourceFiles/settings/settings_scale_widget.cpp + SourceFiles/settings/settings_widget.cpp + + SourceFiles/storage/file_download.cpp + SourceFiles/storage/file_upload.cpp + SourceFiles/storage/localimageloader.cpp + SourceFiles/storage/localstorage.cpp + SourceFiles/storage/serialize_common.cpp + SourceFiles/storage/serialize_document.cpp + + SourceFiles/ui/effects/cross_animation.cpp + SourceFiles/ui/effects/panel_animation.cpp + SourceFiles/ui/effects/radial_animation.cpp + SourceFiles/ui/effects/ripple_animation.cpp + SourceFiles/ui/effects/round_checkbox.cpp + SourceFiles/ui/effects/send_action_animations.cpp + SourceFiles/ui/effects/slide_animation.cpp + SourceFiles/ui/effects/widget_fade_wrap.cpp + SourceFiles/ui/effects/widget_slide_wrap.cpp + + SourceFiles/ui/style/style_core.cpp + SourceFiles/ui/style/style_core_color.cpp + SourceFiles/ui/style/style_core_font.cpp + SourceFiles/ui/style/style_core_icon.cpp + SourceFiles/ui/style/style_core_types.cpp + + SourceFiles/ui/text/text.cpp + SourceFiles/ui/text/text_block.cpp + SourceFiles/ui/text/text_entity.cpp + + SourceFiles/ui/toast/toast.cpp + SourceFiles/ui/toast/toast_manager.cpp + SourceFiles/ui/toast/toast_widget.cpp + + SourceFiles/ui/widgets/buttons.cpp + SourceFiles/ui/widgets/checkbox.cpp + SourceFiles/ui/widgets/continuous_sliders.cpp + SourceFiles/ui/widgets/discrete_sliders.cpp + SourceFiles/ui/widgets/dropdown_menu.cpp + SourceFiles/ui/widgets/inner_dropdown.cpp + SourceFiles/ui/widgets/input_fields.cpp + SourceFiles/ui/widgets/labels.cpp + SourceFiles/ui/widgets/menu.cpp + SourceFiles/ui/widgets/multi_select.cpp + SourceFiles/ui/widgets/popup_menu.cpp + SourceFiles/ui/widgets/scroll_area.cpp + SourceFiles/ui/widgets/shadow.cpp + SourceFiles/ui/widgets/tooltip.cpp + + SourceFiles/ui/abstract_button.cpp + SourceFiles/ui/animation.cpp + SourceFiles/ui/countryinput.cpp + SourceFiles/ui/emoji_config.cpp + SourceFiles/ui/images.cpp + SourceFiles/ui/special_buttons.cpp + SourceFiles/ui/twidget.cpp + + SourceFiles/window/themes/window_theme.cpp + SourceFiles/window/themes/window_theme_editor.cpp + SourceFiles/window/themes/window_theme_editor_block.cpp + SourceFiles/window/themes/window_theme_preview.cpp + SourceFiles/window/themes/window_theme_warning.cpp + + SourceFiles/window/main_window.cpp + SourceFiles/window/notifications_manager.cpp + SourceFiles/window/notifications_manager_default.cpp + SourceFiles/window/notifications_utilities.cpp + SourceFiles/window/player_wrap_widget.cpp + SourceFiles/window/section_widget.cpp + SourceFiles/window/top_bar_widget.cpp + SourceFiles/window/window_controller.cpp + SourceFiles/window/window_main_menu.cpp + SourceFiles/window/window_slide_animation.cpp + + SourceFiles/apiwrap.cpp + SourceFiles/app.cpp + SourceFiles/application.cpp + SourceFiles/auth_session.cpp + SourceFiles/facades.cpp + SourceFiles/layerwidget.cpp + SourceFiles/layout.cpp + SourceFiles/logs.cpp + SourceFiles/main.cpp + SourceFiles/mainwidget.cpp + SourceFiles/mainwindow.cpp + SourceFiles/mediaview.cpp + SourceFiles/messenger.cpp + SourceFiles/observer_peer.cpp + SourceFiles/overviewwidget.cpp + SourceFiles/passcodewidget.cpp + SourceFiles/qt_functions.cpp + SourceFiles/settings.cpp + SourceFiles/shortcuts.cpp + SourceFiles/structs.cpp +) + +set(PLAT_SRC) + +if (APPLE) + set(PLAT_SRC ${PLAT_SRC} + SourceFiles/platform/mac/file_utilities_mac.mm + SourceFiles/platform/mac/mac_utilities.mm + SourceFiles/platform/mac/main_window_mac.mm + SourceFiles/platform/mac/notifications_manager_mac.mm + SourceFiles/platform/mac/specific_mac.mm + SourceFiles/platform/mac/specific_mac_p.mm + SourceFiles/platform/mac/window_title_mac.mm + ) + set(tg_RESOURCES Resources/qrc/telegram_mac.qrc) +endif() +if (WIN32) + set(PLAT_SRC ${PLAT_SRC} + SourceFiles/platform/win/audio_win.cpp + SourceFiles/platform/win/file_utilities_win.cpp + SourceFiles/platform/win/main_window_win.cpp + SourceFiles/platform/win/notifications_manager_win.cpp + SourceFiles/platform/win/specific_win.cpp + SourceFiles/platform/win/window_title_win.cpp + SourceFiles/platform/win/windows_app_user_model_id.cpp + SourceFiles/platform/win/windows_dlls.cpp + SourceFiles/platform/win/windows_event_filter.cpp + ) + set(tg_RESOURCES Resources/qrc/telegram_wnd.qrc) +endif() +if (WINRT) + set(PLAT_SRC ${PLAT_SRC} + SourceFiles/platform/winrt/main_window_winrt.cpp + ) +endif() +if (LINUX) + set(PLAT_SRC ${PLAT_SRC} + SourceFiles/platform/linux/file_utilities_linux.cpp + SourceFiles/platform/linux/linux_desktop_environment.cpp + SourceFiles/platform/linux/linux_gdk_helper.cpp + SourceFiles/platform/linux/linux_libnotify.cpp + SourceFiles/platform/linux/linux_libs.cpp + SourceFiles/platform/linux/main_window_linux.cpp + SourceFiles/platform/linux/notifications_manager_linux.cpp + SourceFiles/platform/linux/specific_linux.cpp + ) + set(tg_RESOURCES Resources/qrc/telegram_linux.qrc) +endif() + +list(APPEND tg_RESOURCES + Resources/qrc/telegram.qrc + Resources/qrc/telegram_sounds.qrc + Resources/qrc/telegram_emoji.qrc + Resources/qrc/telegram_emoji_large.qrc +) + +qt5_add_resources(tg_RESOURCES_RCC ${tg_RESOURCES}) + +set(THIRD_PARTY_SRC) + +if (APPLE) + list(APPEND THIRD_PARTY_SRC + ThirdParty/SPMediaKeyTap/SPMediaKeyTap.m + ThirdParty/SPMediaKeyTap/SPInvocationGrabbing/NSObject+SPInvocationGrabbing.m + ) + include_directories(ThirdParty/SPMediaKeyTap) +endif() + +list(APPEND THIRD_PARTY_SRC + ThirdParty/minizip/ioapi.c + ThirdParty/minizip/zip.c + ThirdParty/minizip/unzip.c + + ThirdParty/emoji_suggestions/emoji_suggestions.cpp +) + +include_directories(ThirdParty) # For minizip/ but we use fully-qualified include path to avoid ambiguity +include_directories(ThirdParty/GSL/include ThirdParty/variant/include + ThirdParty/emoji_suggestions ThirdParty/libtgvoip) + +##====================== +## Telegram +##====================== + +include_directories(SourceFiles SourceFiles/core) + +include_directories(${OPENAL_INCLUDE_DIR} ${ZLIB_INCLUDE_DIRS} + ${LIBZIP_INCLUDE_DIR_ZIP} ${LIBZIP_INCLUDE_DIR_ZIPCONF} + ${OPENSSL_INCLUDE_DIR} ${LIBLZMA_INCLUDE_DIRS} + ${ICONV_INCLUDE_DIR} ${OPUS_INCLUDE_DIR} + ${FFMPEG_INCLUDE_DIRS}) + +add_subdirectory(ThirdParty/libtgvoip) + +# Shut up for testbuilding, remove me +include_directories(/usr/local/opt/openal-soft/include) +# End remove me + +if(NOT WIN32) + add_definitions(-Wno-switch) +endif() + +if (WIN32) + add_definitions(-D_CRT_SECURE_NO_WARNINGS -DWIN32 -D_WINDOWS -DUNICODE -DWIN64 -DWINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP) + list(APPEND APP_SRC Resources/winrc/Telegram.rc) +endif() + +add_definitions(-DTDESKTOP_DISABLE_CRASH_REPORTS) + +if (APPLE) + set(MACOSX_BUNDLE_ICON_FILE Icon.icns) + + add_custom_command( + COMMENT "Generating icon file" + OUTPUT + ${CMAKE_CURRENT_BINARY_DIR}/${MACOSX_BUNDLE_ICON_FILE} + COMMAND + iconutil -c icns -o ${CMAKE_CURRENT_BINARY_DIR}/${MACOSX_BUNDLE_ICON_FILE} ${CMAKE_CURRENT_SOURCE_DIR}/Telegram/Images.xcassets/Icon.iconset/ + WORKING_DIRECTORY . + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/Telegram/Images.xcassets/Icon.iconset + MAIN_DEPENDENCY ${CMAKE_CURRENT_SOURCE_DIR}/Telegram/Images.xcassets/Icon.iconset + ) + add_custom_target(iconset_output + DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${MACOSX_BUNDLE_ICON_FILE}) + + set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/${MACOSX_BUNDLE_ICON_FILE} + PROPERTIES + MACOSX_PACKAGE_LOCATION Resources) + set(APPLE_BUNDLE_SRC ${CMAKE_CURRENT_BINARY_DIR}/${MACOSX_BUNDLE_ICON_FILE}) +endif() + +add_executable(Telegram WIN32 MACOSX_BUNDLE + ${APP_SRC} + ${PLAT_SRC} + ${THIRD_PARTY_SRC} + ${tg_RESOURCES} + ${tg_RESOURCES_RCC} + ${APPLE_BUNDLE_SRC} +) + +# Disable a single annoying warning about c++17 +if(NOT WIN32) + target_compile_options(Telegram PRIVATE -Wno-c++1z-extensions) +endif() + +# Enable C++14 support for msvc (@todo this should be done in cmake) +if(WIN32) + target_compile_options(Telegram PRIVATE /std:c++14) +endif() + +target_compile_definitions(Telegram PRIVATE ${FFMPEG_DEFINITIONS}) + +target_link_libraries(Telegram + Qt5::Core + Qt5::Widgets + Qt5::Network + Qt5::GuiPrivate + tgvoip + ${OPENAL_LIBRARY} + ${FFMPEG_LIBRARIES} + ${ZLIB_LIBRARIES} + ${SWRESAMPLE_LIBRARIES} + ${SWSCALE_LIBRARIES} + ${OPENSSL_LIBRARIES} + ${OPUS_LIB} + ${CONAN_LIBS} +) # crashpad::crashpad_client) + +add_dependencies(Telegram boxes_styles_output) + +if (APPLE) + add_dependencies(Telegram iconset_output) + + set_target_properties(Telegram + PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Telegram.plist + ) + find_library(COREFOUNDATION_LIB CoreFoundation) + find_library(COREAUDIO_LIB CoreAudio) + find_library(AUDIOUNIT_LIB AudioUnit) + find_library(AUDIOTOOLBOX_LIB AudioToolbox) + find_library(COCOA_LIB Cocoa) + find_library(CARBON_LIB Carbon) + find_library(IOKIT_LIB IOKit) + target_link_libraries(Telegram + ${COREFOUNDATION_LIB} + ${COCOA_LIB} + ${CARBON_LIB} + ${COREAUDIO_LIB} + ${AUDIOUNIT_LIB} + ${AUDIOTOOLBOX_LIB} + ${IOKIT_LIB} + ) +endif() + +if(WIN32) + target_link_libraries(Telegram winmm imm32 ws2_32 kernel32 user32 gdi32 winspool comdlg32 advapi32 shell32 ole32 oleaut32 uuid odbc32 odbccp32 Shlwapi Iphlpapi Gdiplus Strmiids) +endif() + +set_target_properties(Telegram + PROPERTIES + COTIRE_CXX_PREFIX_HEADER_INIT SourceFiles/stdafx.h + COTIRE_ADD_UNITY_BUILD FALSE +) +cotire(Telegram) + +# See https://github.com/sakra/cotire/blob/master/MANUAL.md#objective-c +# ObjC and ObjC++ files cannot be cotired, so they have to include appropriate Qt and Tg +# headers themselves, this applies to macOS platform sources. diff --git a/Telegram/Patches/mini_chromium.diff b/Telegram/Patches/mini_chromium.diff deleted file mode 100644 index 3dab62ec2..000000000 --- a/Telegram/Patches/mini_chromium.diff +++ /dev/null @@ -1,52 +0,0 @@ -diff --git a/base/mac/scoped_nsobject.h b/base/mac/scoped_nsobject.h -index 2e157a4..5a306a1 100644 ---- a/base/mac/scoped_nsobject.h -+++ b/base/mac/scoped_nsobject.h -@@ -11,6 +11,7 @@ - - #include "base/compiler_specific.h" - #include "base/mac/scoped_typeref.h" -+#include "base/template_util.h" - - namespace base { - -@@ -55,7 +56,7 @@ class scoped_nsobject : public scoped_nsprotocol { - public: - using scoped_nsprotocol::scoped_nsprotocol; - -- static_assert(std::is_same::value == false, -+ static_assert(is_same::value == false, - "Use ScopedNSAutoreleasePool instead"); - }; - -diff --git a/base/macros.h b/base/macros.h -index 5d96783..096704c 100644 ---- a/base/macros.h -+++ b/base/macros.h -@@ -42,8 +42,9 @@ char (&ArraySizeHelper(const T (&array)[N]))[N]; - - template - inline Dest bit_cast(const Source& source) { -+#if __cplusplus >= 201103L - static_assert(sizeof(Dest) == sizeof(Source), "sizes must be equal"); -- -+#endif - Dest dest; - memcpy(&dest, &source, sizeof(dest)); - return dest; -diff --git a/build/common.gypi b/build/common.gypi -index 1affc70..6e8f292 100644 ---- a/build/common.gypi -+++ b/build/common.gypi -@@ -66,6 +66,11 @@ - 'conditions': [ - ['clang!=0', { - 'CLANG_CXX_LANGUAGE_STANDARD': 'c++11', # -std=c++11 -+ 'conditions': [ -+ ['mac_deployment_target=="10.8"', { -+ 'CLANG_CXX_LIBRARY': 'libc++', # force -stdlib=libc++ for 10.8 -+ }] -+ ], - - # Don't link in libarclite_macosx.a, see http://crbug.com/156530. - 'CLANG_LINK_OBJC_RUNTIME': 'NO', # -fno-objc-link-runtime diff --git a/Telegram/Patches/openal.diff b/Telegram/Patches/openal.diff deleted file mode 100644 index b2a71ad17..000000000 --- a/Telegram/Patches/openal.diff +++ /dev/null @@ -1,22 +0,0 @@ -diff --git a/Alc/backends/winmm.c b/Alc/backends/winmm.c -index 9d8f8e9..8c8e44a 100644 ---- a/Alc/backends/winmm.c -+++ b/Alc/backends/winmm.c -@@ -219,7 +219,7 @@ FORCE_ALIGN static int ALCwinmmPlayback_mixerProc(void *arg) - SetRTPriority(); - althrd_setname(althrd_current(), MIXER_THREAD_NAME); - -- while(GetMessage(&msg, NULL, 0, 0)) -+ if (!self->killNow) while(GetMessage(&msg, NULL, 0, 0)) - { - if(msg.message != WOM_DONE) - continue; -@@ -504,7 +504,7 @@ static int ALCwinmmCapture_captureProc(void *arg) - - althrd_setname(althrd_current(), RECORD_THREAD_NAME); - -- while(GetMessage(&msg, NULL, 0, 0)) -+ if (!self->killNow) while(GetMessage(&msg, NULL, 0, 0)) - { - if(msg.message != WIM_DATA) - continue; diff --git a/Telegram/SetupFiles/data b/Telegram/SetupFiles/data deleted file mode 100644 index e69de29bb..000000000 diff --git a/Telegram/SetupFiles/log.txt b/Telegram/SetupFiles/log.txt deleted file mode 100644 index e69de29bb..000000000 diff --git a/Telegram/SourceFiles/_other/packer.cpp b/Telegram/SourceFiles/_other/packer.cpp deleted file mode 100644 index 4fe9530dc..000000000 --- a/Telegram/SourceFiles/_other/packer.cpp +++ /dev/null @@ -1,539 +0,0 @@ -/* -This file is part of Telegram Desktop, -the official desktop version of Telegram messaging app, see https://telegram.org - -Telegram Desktop is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -It is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -In addition, as a special exception, the copyright holders give permission -to link the code of portions of this program with the OpenSSL library. - -Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE -Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org -*/ -#include "packer.h" - -#include - -#ifdef Q_OS_MAC -//Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin) -#endif - -bool AlphaChannel = false; -quint64 BetaVersion = 0; - -const char *PublicKey = "\ ------BEGIN RSA PUBLIC KEY-----\n\ -MIGJAoGBAMA4ViQrjkPZ9xj0lrer3r23JvxOnrtE8nI69XLGSr+sRERz9YnUptnU\n\ -BZpkIfKaRcl6XzNJiN28cVwO1Ui5JSa814UAiDHzWUqCaXUiUEQ6NmNTneiGx2sQ\n\ -+9PKKlb8mmr3BB9A45ZNwLT6G9AK3+qkZLHojeSA+m84/a6GP4svAgMBAAE=\n\ ------END RSA PUBLIC KEY-----\ -"; - -const char *PublicAlphaKey = "\ ------BEGIN RSA PUBLIC KEY-----\n\ -MIGJAoGBALWu9GGs0HED7KG7BM73CFZ6o0xufKBRQsdnq3lwA8nFQEvmdu+g/I1j\n\ -0LQ+0IQO7GW4jAgzF/4+soPDb6uHQeNFrlVx1JS9DZGhhjZ5rf65yg11nTCIHZCG\n\ -w/CVnbwQOw0g5GBwwFV3r0uTTvy44xx8XXxk+Qknu4eBCsmrAFNnAgMBAAE=\n\ ------END RSA PUBLIC KEY-----\ -"; - -extern const char *PrivateKey; -extern const char *PrivateAlphaKey; -#include "../../../../TelegramPrivate/packer_private.h" // RSA PRIVATE KEYS for update signing -#include "../../../../TelegramPrivate/beta_private.h" // private key for beta version file generation - -QString countBetaVersionSignature(quint64 version); - -// sha1 hash -typedef unsigned char uchar; -typedef unsigned int uint32; -typedef signed int int32; - -namespace{ - -inline uint32 sha1Shift(uint32 v, uint32 shift) { - return ((v << shift) | (v >> (32 - shift))); -} - -void sha1PartHash(uint32 *sha, uint32 *temp) { - uint32 a = sha[0], b = sha[1], c = sha[2], d = sha[3], e = sha[4], round = 0; - -#define _shiftswap(f, v) { \ - uint32 t = sha1Shift(a, 5) + (f) + e + v + temp[round]; \ - e = d; \ - d = c; \ - c = sha1Shift(b, 30); \ - b = a; \ - a = t; \ - ++round; \ - } - -#define _shiftshiftswap(f, v) { \ - temp[round] = sha1Shift((temp[round - 3] ^ temp[round - 8] ^ temp[round - 14] ^ temp[round - 16]), 1); \ - _shiftswap(f, v) \ - } - - while (round < 16) _shiftswap((b & c) | (~b & d), 0x5a827999) - while (round < 20) _shiftshiftswap((b & c) | (~b & d), 0x5a827999) - while (round < 40) _shiftshiftswap(b ^ c ^ d, 0x6ed9eba1) - while (round < 60) _shiftshiftswap((b & c) | (b & d) | (c & d), 0x8f1bbcdc) - while (round < 80) _shiftshiftswap(b ^ c ^ d, 0xca62c1d6) - -#undef _shiftshiftswap -#undef _shiftswap - - sha[0] += a; - sha[1] += b; - sha[2] += c; - sha[3] += d; - sha[4] += e; -} - -} // namespace - -int32 *hashSha1(const void *data, uint32 len, void *dest) { - const uchar *buf = (const uchar *)data; - - uint32 temp[80], block = 0, end; - uint32 sha[5] = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0}; - for (end = block + 64; block + 64 <= len; end = block + 64) { - for (uint32 i = 0; block < end; block += 4) { - temp[i++] = (uint32) buf[block + 3] - | (((uint32) buf[block + 2]) << 8) - | (((uint32) buf[block + 1]) << 16) - | (((uint32) buf[block]) << 24); - } - sha1PartHash(sha, temp); - } - - end = len - block; - memset(temp, 0, sizeof(uint32) * 16); - uint32 last = 0; - for (; last < end; ++last) { - temp[last >> 2] |= (uint32)buf[last + block] << ((3 - (last & 0x03)) << 3); - } - temp[last >> 2] |= 0x80 << ((3 - (last & 3)) << 3); - if (end >= 56) { - sha1PartHash(sha, temp); - memset(temp, 0, sizeof(uint32) * 16); - } - temp[15] = len << 3; - sha1PartHash(sha, temp); - - uchar *sha1To = (uchar*)dest; - - for (int32 i = 19; i >= 0; --i) { - sha1To[i] = (sha[i >> 2] >> (((3 - i) & 0x03) << 3)) & 0xFF; - } - - return (int32*)sha1To; -} - -QString BetaSignature; - -int main(int argc, char *argv[]) -{ - QString workDir; - - QString remove; - int version = 0; - bool target32 = false; - QFileInfoList files; - for (int i = 0; i < argc; ++i) { - if (string("-path") == argv[i] && i + 1 < argc) { - QString path = workDir + QString(argv[i + 1]); - QFileInfo info(path); - files.push_back(info); - if (remove.isEmpty()) remove = info.canonicalPath() + "/"; - } else if (string("-target") == argv[i] && i + 1 < argc) { - target32 = (string("mac32") == argv[i + 1]); - } else if (string("-version") == argv[i] && i + 1 < argc) { - version = QString(argv[i + 1]).toInt(); - } else if (string("-alpha") == argv[i]) { - AlphaChannel = true; - } else if (string("-beta") == argv[i] && i + 1 < argc) { - BetaVersion = QString(argv[i + 1]).toULongLong(); - if (BetaVersion > version * 1000ULL && BetaVersion < (version + 1) * 1000ULL) { - AlphaChannel = false; - BetaSignature = countBetaVersionSignature(BetaVersion); - if (BetaSignature.isEmpty()) { - return -1; - } - } else { - cout << "Bad -beta param value passed, should be for the same version: " << version << ", beta: " << BetaVersion << "\n"; - return -1; - } - } - } - - if (files.isEmpty() || remove.isEmpty() || version <= 1016 || version > 999999999) { -#ifdef Q_OS_WIN - cout << "Usage: Packer.exe -path {file} -version {version} OR Packer.exe -path {dir} -version {version}\n"; -#elif defined Q_OS_MAC - cout << "Usage: Packer.app -path {file} -version {version} OR Packer.app -path {dir} -version {version}\n"; -#else - cout << "Usage: Packer -path {file} -version {version} OR Packer -path {dir} -version {version}\n"; -#endif - return -1; - } - - bool hasDirs = true; - while (hasDirs) { - hasDirs = false; - for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) { - QFileInfo info(*i); - QString fullPath = info.canonicalFilePath(); - if (info.isDir()) { - hasDirs = true; - files.erase(i); - QDir d = QDir(info.absoluteFilePath()); - QString fullDir = d.canonicalPath(); - QStringList entries = d.entryList(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot); - files.append(d.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot)); - break; - } else if (!info.isReadable()) { - cout << "Can't read: " << info.absoluteFilePath().toUtf8().constData() << "\n"; - return -1; - } else if (info.isHidden()) { - hasDirs = true; - files.erase(i); - break; - } - } - } - for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) { - QFileInfo info(*i); - if (!info.canonicalFilePath().startsWith(remove)) { - cout << "Can't find '" << remove.toUtf8().constData() << "' in file '" << info.canonicalFilePath().toUtf8().constData() << "' :(\n"; - return -1; - } - } - - QByteArray result; - { - QBuffer buffer(&result); - buffer.open(QIODevice::WriteOnly); - QDataStream stream(&buffer); - stream.setVersion(QDataStream::Qt_5_1); - - if (BetaVersion) { - stream << quint32(0x7FFFFFFF); - stream << quint64(BetaVersion); - } else { - stream << quint32(version); - } - - stream << quint32(files.size()); - cout << "Found " << files.size() << " file" << (files.size() == 1 ? "" : "s") << "..\n"; - for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) { - QFileInfo info(*i); - QString fullName = info.canonicalFilePath(); - QString name = fullName.mid(remove.length()); - cout << name.toUtf8().constData() << " (" << info.size() << ")\n"; - - QFile f(fullName); - if (!f.open(QIODevice::ReadOnly)) { - cout << "Can't open '" << fullName.toUtf8().constData() << "' for read..\n"; - return -1; - } - QByteArray inner = f.readAll(); - stream << name << quint32(inner.size()) << inner; -#if defined Q_OS_MAC || defined Q_OS_LINUX - stream << (QFileInfo(fullName).isExecutable() ? true : false); -#endif - } - if (stream.status() != QDataStream::Ok) { - cout << "Stream status is bad: " << stream.status() << "\n"; - return -1; - } - } - - int32 resultSize = result.size(); - cout << "Compression start, size: " << resultSize << "\n"; - - QByteArray compressed, resultCheck; -#ifdef Q_OS_WIN // use Lzma SDK for win - const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header - - compressed.resize(hSize + resultSize + 1024 * 1024); // rsa signature + sha1 + lzma props + max compressed size - - size_t compressedLen = compressed.size() - hSize; - size_t outPropsSize = LZMA_PROPS_SIZE; - uchar *_dest = (uchar*)(compressed.data() + hSize); - size_t *_destLen = &compressedLen; - const uchar *_src = (const uchar*)(result.constData()); - size_t _srcLen = result.size(); - uchar *_outProps = (uchar*)(compressed.data() + hSigLen + hShaLen); - int res = LzmaCompress(_dest, _destLen, _src, _srcLen, _outProps, &outPropsSize, 9, 64 * 1024 * 1024, 4, 0, 2, 273, 2); - if (res != SZ_OK) { - cout << "Error in compression: " << res << "\n"; - return -1; - } - compressed.resize(int(hSize + compressedLen)); - memcpy(compressed.data() + hSigLen + hShaLen + hPropsLen, &resultSize, hOriginalSizeLen); - - cout << "Compressed to size: " << compressedLen << "\n"; - - cout << "Checking uncompressed..\n"; - - int32 resultCheckLen; - memcpy(&resultCheckLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen); - if (resultCheckLen <= 0 || resultCheckLen > 1024 * 1024 * 1024) { - cout << "Bad result len: " << resultCheckLen << "\n"; - return -1; - } - resultCheck.resize(resultCheckLen); - - size_t resultLen = resultCheck.size(); - SizeT srcLen = compressedLen; - int uncompressRes = LzmaUncompress((uchar*)resultCheck.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE); - if (uncompressRes != SZ_OK) { - cout << "Uncompress failed: " << uncompressRes << "\n"; - return -1; - } - if (resultLen != size_t(result.size())) { - cout << "Uncompress bad size: " << resultLen << ", was: " << result.size() << "\n"; - return -1; - } -#else // use liblzma for others - const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header - - compressed.resize(hSize + resultSize + 1024 * 1024); // rsa signature + sha1 + lzma props + max compressed size - - size_t compressedLen = compressed.size() - hSize; - - lzma_stream stream = LZMA_STREAM_INIT; - - int preset = 9 | LZMA_PRESET_EXTREME; - lzma_ret ret = lzma_easy_encoder(&stream, preset, LZMA_CHECK_CRC64); - if (ret != LZMA_OK) { - const char *msg; - switch (ret) { - case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; - case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break; - case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break; - default: msg = "Unknown error, possibly a bug"; break; - } - cout << "Error initializing the encoder: " << msg << " (error code " << ret << ")\n"; - return -1; - } - - stream.avail_in = resultSize; - stream.next_in = (uint8_t*)result.constData(); - stream.avail_out = compressedLen; - stream.next_out = (uint8_t*)(compressed.data() + hSize); - - lzma_ret res = lzma_code(&stream, LZMA_FINISH); - compressedLen -= stream.avail_out; - lzma_end(&stream); - if (res != LZMA_OK && res != LZMA_STREAM_END) { - const char *msg; - switch (res) { - case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; - case LZMA_DATA_ERROR: msg = "File size limits exceeded"; break; - default: msg = "Unknown error, possibly a bug"; break; - } - cout << "Error in compression: " << msg << " (error code " << res << ")\n"; - return -1; - } - - compressed.resize(int(hSize + compressedLen)); - memcpy(compressed.data() + hSigLen + hShaLen, &resultSize, hOriginalSizeLen); - - cout << "Compressed to size: " << compressedLen << "\n"; - - cout << "Checking uncompressed..\n"; - - int32 resultCheckLen; - memcpy(&resultCheckLen, compressed.constData() + hSigLen + hShaLen, hOriginalSizeLen); - if (resultCheckLen <= 0 || resultCheckLen > 1024 * 1024 * 1024) { - cout << "Bad result len: " << resultCheckLen << "\n"; - return -1; - } - resultCheck.resize(resultCheckLen); - - size_t resultLen = resultCheck.size(); - - stream = LZMA_STREAM_INIT; - - ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED); - if (ret != LZMA_OK) { - const char *msg; - switch (ret) { - case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; - case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break; - case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break; - default: msg = "Unknown error, possibly a bug"; break; - } - cout << "Error initializing the decoder: " << msg << " (error code " << ret << ")\n"; - return -1; - } - - stream.avail_in = compressedLen; - stream.next_in = (uint8_t*)(compressed.constData() + hSize); - stream.avail_out = resultLen; - stream.next_out = (uint8_t*)resultCheck.data(); - - res = lzma_code(&stream, LZMA_FINISH); - if (stream.avail_in) { - cout << "Error in decompression, " << stream.avail_in << " bytes left in _in of " << compressedLen << " whole.\n"; - return -1; - } else if (stream.avail_out) { - cout << "Error in decompression, " << stream.avail_out << " bytes free left in _out of " << resultLen << " whole.\n"; - return -1; - } - lzma_end(&stream); - if (res != LZMA_OK && res != LZMA_STREAM_END) { - const char *msg; - switch (res) { - case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; - case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break; - case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break; - case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break; - case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break; - default: msg = "Unknown error, possibly a bug"; break; - } - cout << "Error in decompression: " << msg << " (error code " << res << ")\n"; - return -1; - } -#endif - if (memcmp(result.constData(), resultCheck.constData(), resultLen)) { - cout << "Data differ :(\n"; - return -1; - } - /**/ - result = resultCheck = QByteArray(); - - cout << "Counting SHA1 hash..\n"; - - uchar sha1Buffer[20]; - memcpy(compressed.data() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, uint32(compressedLen + hPropsLen + hOriginalSizeLen), sha1Buffer), hShaLen); // count sha1 - - uint32 siglen = 0; - - cout << "Signing..\n"; - RSA *prKey = PEM_read_bio_RSAPrivateKey(BIO_new_mem_buf(const_cast((AlphaChannel || BetaVersion) ? PrivateAlphaKey : PrivateKey), -1), 0, 0, 0); - if (!prKey) { - cout << "Could not read RSA private key!\n"; - return -1; - } - if (RSA_size(prKey) != hSigLen) { - cout << "Bad private key, size: " << RSA_size(prKey) << "\n"; - RSA_free(prKey); - return -1; - } - if (RSA_sign(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (uchar*)(compressed.data()), &siglen, prKey) != 1) { // count signature - cout << "Signing failed!\n"; - RSA_free(prKey); - return -1; - } - RSA_free(prKey); - - if (siglen != hSigLen) { - cout << "Bad signature length: " << siglen << "\n"; - return -1; - } - - cout << "Checking signature..\n"; - RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast((AlphaChannel || BetaVersion) ? PublicAlphaKey : PublicKey), -1), 0, 0, 0); - if (!pbKey) { - cout << "Could not read RSA public key!\n"; - return -1; - } - if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), siglen, pbKey) != 1) { // verify signature - RSA_free(pbKey); - cout << "Signature verification failed!\n"; - return -1; - } - cout << "Signature verified!\n"; - RSA_free(pbKey); -#ifdef Q_OS_WIN - QString outName(QString("tupdate%1").arg(BetaVersion ? BetaVersion : version)); -#elif defined Q_OS_MAC - QString outName((target32 ? QString("tmac32upd%1") : QString("tmacupd%1")).arg(BetaVersion ? BetaVersion : version)); -#elif defined Q_OS_LINUX32 - QString outName(QString("tlinux32upd%1").arg(BetaVersion ? BetaVersion : version)); -#elif defined Q_OS_LINUX64 - QString outName(QString("tlinuxupd%1").arg(BetaVersion ? BetaVersion : version)); -#else -#error Unknown platform! -#endif - if (BetaVersion) { - outName += "_" + BetaSignature; - } - QFile out(outName); - if (!out.open(QIODevice::WriteOnly)) { - cout << "Can't open '" << outName.toUtf8().constData() << "' for write..\n"; - return -1; - } - out.write(compressed); - out.close(); - - if (BetaVersion) { - QString keyName(QString("tbeta_%1_key").arg(BetaVersion)); - QFile key(keyName); - if (!key.open(QIODevice::WriteOnly)) { - cout << "Can't open '" << keyName.toUtf8().constData() << "' for write..\n"; - return -1; - } - key.write(BetaSignature.toUtf8()); - key.close(); - } - - cout << "Update file '" << outName.toUtf8().constData() << "' written successfully!\n"; - - return 0; -} - -QString countBetaVersionSignature(quint64 version) { // duplicated in autoupdate.cpp - QByteArray cBetaPrivateKey(BetaPrivateKey); - if (cBetaPrivateKey.isEmpty()) { - cout << "Error: Trying to count beta version signature without beta private key!\n"; - return QString(); - } - - QByteArray signedData = (QLatin1String("TelegramBeta_") + QString::number(version, 16).toLower()).toUtf8(); - - static const int32 shaSize = 20, keySize = 128; - - uchar sha1Buffer[shaSize]; - hashSha1(signedData.constData(), signedData.size(), sha1Buffer); // count sha1 - - uint32 siglen = 0; - - RSA *prKey = PEM_read_bio_RSAPrivateKey(BIO_new_mem_buf(const_cast(cBetaPrivateKey.constData()), -1), 0, 0, 0); - if (!prKey) { - cout << "Error: Could not read beta private key!\n"; - return QString(); - } - if (RSA_size(prKey) != keySize) { - cout << "Error: Bad beta private key size: " << RSA_size(prKey) << "\n"; - RSA_free(prKey); - return QString(); - } - QByteArray signature; - signature.resize(keySize); - if (RSA_sign(NID_sha1, (const uchar*)(sha1Buffer), shaSize, (uchar*)(signature.data()), &siglen, prKey) != 1) { // count signature - cout << "Error: Counting beta version signature failed!\n"; - RSA_free(prKey); - return QString(); - } - RSA_free(prKey); - - if (siglen != keySize) { - cout << "Error: Bad beta version signature length: " << siglen << "\n"; - return QString(); - } - - signature = signature.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); - signature = signature.replace('-', '8').replace('_', 'B'); - return QString::fromUtf8(signature.mid(19, 32)); -} diff --git a/Telegram/SourceFiles/_other/packer.h b/Telegram/SourceFiles/_other/packer.h deleted file mode 100644 index 2cef45d82..000000000 --- a/Telegram/SourceFiles/_other/packer.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -This file is part of Telegram Desktop, -the official desktop version of Telegram messaging app, see https://telegram.org - -Telegram Desktop is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -It is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -In addition, as a special exception, the copyright holders give permission -to link the code of portions of this program with the OpenSSL library. - -Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE -Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org -*/ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include - -#ifdef Q_OS_WIN // use Lzma SDK for win -#include -#else -#include -#endif - -#include -#include -#include -using std::string; -using std::wstring; -using std::cout; \ No newline at end of file diff --git a/Telegram/SourceFiles/_other/updater.cpp b/Telegram/SourceFiles/_other/updater.cpp deleted file mode 100644 index dbcce3137..000000000 --- a/Telegram/SourceFiles/_other/updater.cpp +++ /dev/null @@ -1,590 +0,0 @@ -/* -This file is part of Telegram Desktop, -the official desktop version of Telegram messaging app, see https://telegram.org - -Telegram Desktop is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -It is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -In addition, as a special exception, the copyright holders give permission -to link the code of portions of this program with the OpenSSL library. - -Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE -Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org -*/ -#include "updater.h" - -bool _debug = false; - -wstring updaterName, updaterDir, updateTo, exeName; - -bool equal(const wstring &a, const wstring &b) { - return !_wcsicmp(a.c_str(), b.c_str()); -} - -void updateError(const WCHAR *msg, DWORD errorCode) { - WCHAR errMsg[2048]; - LPWSTR errorText = NULL, errorTextDefault = L"(Unknown error)"; - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&errorText, 0, 0); - if (!errorText) { - errorText = errorTextDefault; - } - wsprintf(errMsg, L"%s, error code: %d\nError message: %s", msg, errorCode, errorText); - - MessageBox(0, errMsg, L"Update error!", MB_ICONERROR); - - if (errorText != errorTextDefault) { - LocalFree(errorText); - } -} - -HANDLE _logFile = 0; -void openLog() { - if (!_debug || _logFile) return; - wstring logPath = L"DebugLogs"; - if (!CreateDirectory(logPath.c_str(), NULL)) { - DWORD errorCode = GetLastError(); - if (errorCode && errorCode != ERROR_ALREADY_EXISTS) { - updateError(L"Failed to create log directory", errorCode); - return; - } - } - - SYSTEMTIME stLocalTime; - - GetLocalTime(&stLocalTime); - - static const int maxFileLen = MAX_PATH * 10; - WCHAR logName[maxFileLen]; - wsprintf(logName, L"DebugLogs\\%04d%02d%02d_%02d%02d%02d_upd.txt", - stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay, - stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond); - _logFile = CreateFile(logName, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); - if (_logFile == INVALID_HANDLE_VALUE) { // :( - updateError(L"Failed to create log file", GetLastError()); - _logFile = 0; - return; - } -} - -void closeLog() { - if (!_logFile) return; - - CloseHandle(_logFile); - _logFile = 0; -} - -void writeLog(const wstring &msg) { - if (!_logFile) return; - - wstring full = msg + L'\n'; - DWORD written = 0; - BOOL result = WriteFile(_logFile, full.c_str(), full.size() * sizeof(wchar_t), &written, 0); - if (!result) { - updateError((L"Failed to write log entry '" + msg + L"'").c_str(), GetLastError()); - closeLog(); - return; - } - BOOL flushr = FlushFileBuffers(_logFile); - if (!flushr) { - updateError((L"Failed to flush log on entry '" + msg + L"'").c_str(), GetLastError()); - closeLog(); - return; - } -} - -void fullClearPath(const wstring &dir) { - WCHAR path[4096]; - memcpy(path, dir.c_str(), (dir.size() + 1) * sizeof(WCHAR)); - path[dir.size() + 1] = 0; - writeLog(L"Fully clearing path '" + dir + L"'.."); - SHFILEOPSTRUCT file_op = { - NULL, - FO_DELETE, - path, - L"", - FOF_NOCONFIRMATION | - FOF_NOERRORUI | - FOF_SILENT, - false, - 0, - L"" - }; - int res = SHFileOperation(&file_op); - if (res) writeLog(L"Error: failed to clear path! :("); -} - -void delFolder() { - wstring delPathOld = L"tupdates\\ready", delPath = L"tupdates\\temp", delFolder = L"tupdates"; - fullClearPath(delPathOld); - fullClearPath(delPath); - RemoveDirectory(delFolder.c_str()); -} - -DWORD versionNum = 0, versionLen = 0, readLen = 0; -WCHAR versionStr[32] = { 0 }; - -bool update() { - writeLog(L"Update started.."); - - wstring updDir = L"tupdates\\temp", readyFilePath = L"tupdates\\temp\\ready", tdataDir = L"tupdates\\temp\\tdata"; - { - HANDLE readyFile = CreateFile(readyFilePath.c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); - if (readyFile != INVALID_HANDLE_VALUE) { - CloseHandle(readyFile); - } else { - updDir = L"tupdates\\ready"; // old - tdataDir = L"tupdates\\ready\\tdata"; - } - } - - HANDLE versionFile = CreateFile((tdataDir + L"\\version").c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); - if (versionFile != INVALID_HANDLE_VALUE) { - if (!ReadFile(versionFile, &versionNum, sizeof(DWORD), &readLen, NULL) || readLen != sizeof(DWORD)) { - versionNum = 0; - } else { - if (versionNum == 0x7FFFFFFF) { // beta version - - } else if (!ReadFile(versionFile, &versionLen, sizeof(DWORD), &readLen, NULL) || readLen != sizeof(DWORD) || versionLen > 63) { - versionNum = 0; - } else if (!ReadFile(versionFile, versionStr, versionLen, &readLen, NULL) || readLen != versionLen) { - versionNum = 0; - } - } - CloseHandle(versionFile); - writeLog(L"Version file read."); - } else { - writeLog(L"Could not open version file to update registry :("); - } - - deque dirs; - dirs.push_back(updDir); - - deque from, to, forcedirs; - - do { - wstring dir = dirs.front(); - dirs.pop_front(); - - wstring toDir = updateTo; - if (dir.size() > updDir.size() + 1) { - toDir += (dir.substr(updDir.size() + 1) + L"\\"); - forcedirs.push_back(toDir); - writeLog(L"Parsing dir '" + toDir + L"' in update tree.."); - } - - WIN32_FIND_DATA findData; - HANDLE findHandle = FindFirstFileEx((dir + L"\\*").c_str(), FindExInfoStandard, &findData, FindExSearchNameMatch, 0, 0); - if (findHandle == INVALID_HANDLE_VALUE) { - DWORD errorCode = GetLastError(); - if (errorCode == ERROR_PATH_NOT_FOUND) { // no update is ready - return true; - } - writeLog(L"Error: failed to find update files :("); - updateError(L"Failed to find update files", errorCode); - delFolder(); - return false; - } - - do { - wstring fname = dir + L"\\" + findData.cFileName; - if (fname.substr(0, tdataDir.size()) == tdataDir && (fname.size() <= tdataDir.size() || fname.at(tdataDir.size()) == '/')) { - writeLog(L"Skipped 'tdata' path '" + fname + L"'"); - } else if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { - if (findData.cFileName != wstring(L".") && findData.cFileName != wstring(L"..")) { - dirs.push_back(fname); - writeLog(L"Added dir '" + fname + L"' in update tree.."); - } - } else { - wstring tofname = updateTo + fname.substr(updDir.size() + 1); - if (equal(tofname, updaterName)) { // bad update - has Updater.exe - delete all dir - writeLog(L"Error: bad update, has Updater.exe! '" + tofname + L"' equal '" + updaterName + L"'"); - delFolder(); - return false; - } else if (equal(tofname, updateTo + L"Telegram.exe") && exeName != L"Telegram.exe") { - wstring fullBinaryPath = updateTo + exeName; - writeLog(L"Target binary found: '" + tofname + L"', changing to '" + fullBinaryPath + L"'"); - tofname = fullBinaryPath; - } - if (equal(fname, readyFilePath)) { - writeLog(L"Skipped ready file '" + fname + L"'"); - } else { - from.push_back(fname); - to.push_back(tofname); - writeLog(L"Added file '" + fname + L"' to be copied to '" + tofname + L"'"); - } - } - } while (FindNextFile(findHandle, &findData)); - DWORD errorCode = GetLastError(); - if (errorCode && errorCode != ERROR_NO_MORE_FILES) { // everything is found - writeLog(L"Error: failed to find next update file :("); - updateError(L"Failed to find next update file", errorCode); - delFolder(); - return false; - } - FindClose(findHandle); - } while (!dirs.empty()); - - for (size_t i = 0; i < forcedirs.size(); ++i) { - wstring forcedir = forcedirs[i]; - writeLog(L"Forcing dir '" + forcedir + L"'.."); - if (!forcedir.empty() && !CreateDirectory(forcedir.c_str(), NULL)) { - DWORD errorCode = GetLastError(); - if (errorCode && errorCode != ERROR_ALREADY_EXISTS) { - writeLog(L"Error: failed to create dir '" + forcedir + L"'.."); - updateError(L"Failed to create directory", errorCode); - delFolder(); - return false; - } - writeLog(L"Already exists!"); - } - } - - for (size_t i = 0; i < from.size(); ++i) { - wstring fname = from[i], tofname = to[i]; - BOOL copyResult; - do { - writeLog(L"Copying file '" + fname + L"' to '" + tofname + L"'.."); - int copyTries = 0; - do { - copyResult = CopyFile(fname.c_str(), tofname.c_str(), FALSE); - if (!copyResult) { - ++copyTries; - Sleep(100); - } else { - break; - } - } while (copyTries < 100); - if (!copyResult) { - writeLog(L"Error: failed to copy, asking to retry.."); - WCHAR errMsg[2048]; - wsprintf(errMsg, L"Failed to update Telegram :(\n%s is not accessible.", tofname.c_str()); - if (MessageBox(0, errMsg, L"Update error!", MB_ICONERROR | MB_RETRYCANCEL) != IDRETRY) { - delFolder(); - return false; - } - } - } while (!copyResult); - } - - writeLog(L"Update succeed! Clearing folder.."); - delFolder(); - return true; -} - -void updateRegistry() { - if (versionNum && versionNum != 0x7FFFFFFF) { - writeLog(L"Updating registry.."); - versionStr[versionLen / 2] = 0; - HKEY rkey; - LSTATUS status = RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{53F49750-6209-4FBF-9CA8-7A333C87D1ED}_is1", 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &rkey); - if (status == ERROR_SUCCESS) { - writeLog(L"Checking registry install location.."); - static const int bufSize = 4096; - DWORD locationType, locationSize = bufSize * 2; - WCHAR locationStr[bufSize], exp[bufSize]; - if (RegQueryValueEx(rkey, L"InstallLocation", 0, &locationType, (BYTE*)locationStr, &locationSize) == ERROR_SUCCESS) { - locationSize /= 2; - if (locationStr[locationSize - 1]) { - locationStr[locationSize++] = 0; - } - if (locationType == REG_EXPAND_SZ) { - DWORD copy = ExpandEnvironmentStrings(locationStr, exp, bufSize); - if (copy <= bufSize) { - memcpy(locationStr, exp, copy * sizeof(WCHAR)); - } - } - if (locationType == REG_EXPAND_SZ || locationType == REG_SZ) { - if (PathCanonicalize(exp, locationStr)) { - memcpy(locationStr, exp, bufSize * sizeof(WCHAR)); - if (GetFullPathName(L".", bufSize, exp, 0) < bufSize) { - wstring installpath = locationStr, mypath = exp; - if (installpath == mypath + L"\\" || true) { // always update reg info, if we found it - WCHAR nameStr[bufSize], dateStr[bufSize], publisherStr[bufSize], icongroupStr[bufSize]; - SYSTEMTIME stLocalTime; - GetLocalTime(&stLocalTime); - RegSetValueEx(rkey, L"DisplayVersion", 0, REG_SZ, (BYTE*)versionStr, ((versionLen / 2) + 1) * sizeof(WCHAR)); - wsprintf(nameStr, L"Telegram Desktop version %s", versionStr); - RegSetValueEx(rkey, L"DisplayName", 0, REG_SZ, (BYTE*)nameStr, (wcslen(nameStr) + 1) * sizeof(WCHAR)); - wsprintf(publisherStr, L"Telegram Messenger LLP"); - RegSetValueEx(rkey, L"Publisher", 0, REG_SZ, (BYTE*)publisherStr, (wcslen(publisherStr) + 1) * sizeof(WCHAR)); - wsprintf(icongroupStr, L"Telegram Desktop"); - RegSetValueEx(rkey, L"Inno Setup: Icon Group", 0, REG_SZ, (BYTE*)icongroupStr, (wcslen(icongroupStr) + 1) * sizeof(WCHAR)); - wsprintf(dateStr, L"%04d%02d%02d", stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay); - RegSetValueEx(rkey, L"InstallDate", 0, REG_SZ, (BYTE*)dateStr, (wcslen(dateStr) + 1) * sizeof(WCHAR)); - - WCHAR *appURL = L"https://desktop.telegram.org"; - RegSetValueEx(rkey, L"HelpLink", 0, REG_SZ, (BYTE*)appURL, (wcslen(appURL) + 1) * sizeof(WCHAR)); - RegSetValueEx(rkey, L"URLInfoAbout", 0, REG_SZ, (BYTE*)appURL, (wcslen(appURL) + 1) * sizeof(WCHAR)); - RegSetValueEx(rkey, L"URLUpdateInfo", 0, REG_SZ, (BYTE*)appURL, (wcslen(appURL) + 1) * sizeof(WCHAR)); - } - } - } - } - } - RegCloseKey(rkey); - } - } -} - -int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPWSTR cmdParamarg, int cmdShow) { - openLog(); - - _oldWndExceptionFilter = SetUnhandledExceptionFilter(_exceptionFilter); -// CAPIHook apiHook("kernel32.dll", "SetUnhandledExceptionFilter", (PROC)RedirectedSetUnhandledExceptionFilter); - - writeLog(L"Updaters started.."); - - LPWSTR *args; - int argsCount; - - bool needupdate = false, autostart = false, debug = false, writeprotected = false, startintray = false, testmode = false; - args = CommandLineToArgvW(GetCommandLine(), &argsCount); - if (args) { - for (int i = 1; i < argsCount; ++i) { - if (equal(args[i], L"-update")) { - needupdate = true; - } else if (equal(args[i], L"-autostart")) { - autostart = true; - } else if (equal(args[i], L"-debug")) { - debug = _debug = true; - openLog(); - } else if (equal(args[i], L"-startintray")) { - startintray = true; - } else if (equal(args[i], L"-testmode")) { - testmode = true; - } else if (equal(args[i], L"-writeprotected") && ++i < argsCount) { - writeprotected = true; - updateTo = args[i]; - for (int i = 0, l = updateTo.size(); i < l; ++i) { - if (updateTo[i] == L'/') { - updateTo[i] = L'\\'; - } - } - } else if (equal(args[i], L"-exename") && ++i < argsCount) { - exeName = args[i]; - for (int i = 0, l = exeName.size(); i < l; ++i) { - if (exeName[i] == L'/' || exeName[i] == L'\\') { - exeName = L"Telegram.exe"; - break; - } - } - } - } - if (exeName.empty()) { - exeName = L"Telegram.exe"; - } - if (needupdate) writeLog(L"Need to update!"); - if (autostart) writeLog(L"From autostart!"); - if (writeprotected) writeLog(L"Write Protected folder!"); - - updaterName = args[0]; - writeLog(L"Updater name is: " + updaterName); - if (updaterName.size() > 11) { - if (equal(updaterName.substr(updaterName.size() - 11), L"Updater.exe")) { - updaterDir = updaterName.substr(0, updaterName.size() - 11); - writeLog(L"Updater dir is: " + updaterDir); - if (!writeprotected) { - updateTo = updaterDir; - } - writeLog(L"Update to: " + updateTo); - if (needupdate && update()) { - updateRegistry(); - } - if (writeprotected) { // if we can't clear all tupdates\ready (Updater.exe is there) - clear only version - if (DeleteFile(L"tupdates\\temp\\tdata\\version") || DeleteFile(L"tupdates\\ready\\tdata\\version")) { - writeLog(L"Version file deleted!"); - } else { - writeLog(L"Error: could not delete version file"); - } - } - } else { - writeLog(L"Error: bad exe name!"); - } - } else { - writeLog(L"Error: short exe name!"); - } - LocalFree(args); - } else { - writeLog(L"Error: No command line arguments!"); - } - - wstring targs; - if (autostart) targs += L" -autostart"; - if (debug) targs += L" -debug"; - if (startintray) targs += L" -startintray"; - if (testmode) targs += L" -testmode"; - - bool executed = false; - if (writeprotected) { // run un-elevated - writeLog(L"Trying to run un-elevated by temp.lnk"); - - HRESULT hres = CoInitialize(0); - if (SUCCEEDED(hres)) { - IShellLink* psl; - HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl); - if (SUCCEEDED(hres)) { - IPersistFile* ppf; - - wstring exe = updateTo + exeName, dir = updateTo; - psl->SetArguments((targs.size() ? targs.substr(1) : targs).c_str()); - psl->SetPath(exe.c_str()); - psl->SetWorkingDirectory(dir.c_str()); - psl->SetDescription(L""); - - hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); - - if (SUCCEEDED(hres)) { - wstring lnk = L"tupdates\\temp\\temp.lnk"; - hres = ppf->Save(lnk.c_str(), TRUE); - if (!SUCCEEDED(hres)) { - lnk = L"tupdates\\ready\\temp.lnk"; // old - hres = ppf->Save(lnk.c_str(), TRUE); - } - ppf->Release(); - - if (SUCCEEDED(hres)) { - writeLog(L"Executing un-elevated through link.."); - ShellExecute(0, 0, L"explorer.exe", lnk.c_str(), 0, SW_SHOWNORMAL); - executed = true; - } else { - writeLog(L"Error: ppf->Save failed"); - } - } else { - writeLog(L"Error: Could not create interface IID_IPersistFile"); - } - psl->Release(); - } else { - writeLog(L"Error: could not create instance of IID_IShellLink"); - } - CoUninitialize(); - } else { - writeLog(L"Error: Could not initialize COM"); - } - } - if (!executed) { - ShellExecute(0, 0, (updateTo + exeName).c_str(), (L"-noupdate" + targs).c_str(), 0, SW_SHOWNORMAL); - } - - writeLog(L"Executed '" + exeName + L"', closing log and quitting.."); - closeLog(); - - return 0; -} - -static const WCHAR *_programName = L"Telegram Desktop"; // folder in APPDATA, if current path is unavailable for writing -static const WCHAR *_exeName = L"Updater.exe"; - -LPTOP_LEVEL_EXCEPTION_FILTER _oldWndExceptionFilter = 0; - -typedef BOOL (FAR STDAPICALLTYPE *t_miniDumpWriteDump)( - _In_ HANDLE hProcess, - _In_ DWORD ProcessId, - _In_ HANDLE hFile, - _In_ MINIDUMP_TYPE DumpType, - _In_opt_ PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, - _In_opt_ PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, - _In_opt_ PMINIDUMP_CALLBACK_INFORMATION CallbackParam -); -t_miniDumpWriteDump miniDumpWriteDump = 0; - -HANDLE _generateDumpFileAtPath(const WCHAR *path) { - static const int maxFileLen = MAX_PATH * 10; - - WCHAR szPath[maxFileLen]; - wsprintf(szPath, L"%stdata\\", path); - if (!CreateDirectory(szPath, NULL)) { - if (GetLastError() != ERROR_ALREADY_EXISTS) { - return 0; - } - } - wsprintf(szPath, L"%sdumps\\", path); - if (!CreateDirectory(szPath, NULL)) { - if (GetLastError() != ERROR_ALREADY_EXISTS) { - return 0; - } - } - - WCHAR szFileName[maxFileLen]; - WCHAR szExeName[maxFileLen]; - - wcscpy_s(szExeName, _exeName); - WCHAR *dotFrom = wcschr(szExeName, WCHAR(L'.')); - if (dotFrom) { - wsprintf(dotFrom, L""); - } - - SYSTEMTIME stLocalTime; - - GetLocalTime(&stLocalTime); - - wsprintf(szFileName, L"%s%s-%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp", - szPath, szExeName, updaterVersionStr, - stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay, - stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond, - GetCurrentProcessId(), GetCurrentThreadId()); - return CreateFile(szFileName, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0); -} - -void _generateDump(EXCEPTION_POINTERS* pExceptionPointers) { - static const int maxFileLen = MAX_PATH * 10; - - closeLog(); - - HMODULE hDll = LoadLibrary(L"DBGHELP.DLL"); - if (!hDll) return; - - miniDumpWriteDump = (t_miniDumpWriteDump)GetProcAddress(hDll, "MiniDumpWriteDump"); - if (!miniDumpWriteDump) return; - - HANDLE hDumpFile = 0; - - WCHAR szPath[maxFileLen]; - DWORD len = GetModuleFileName(GetModuleHandle(0), szPath, maxFileLen); - if (!len) return; - - WCHAR *pathEnd = szPath + len; - - if (!_wcsicmp(pathEnd - wcslen(_exeName), _exeName)) { - wsprintf(pathEnd - wcslen(_exeName), L""); - hDumpFile = _generateDumpFileAtPath(szPath); - } - if (!hDumpFile || hDumpFile == INVALID_HANDLE_VALUE) { - WCHAR wstrPath[maxFileLen]; - DWORD wstrPathLen; - if (wstrPathLen = GetEnvironmentVariable(L"APPDATA", wstrPath, maxFileLen)) { - wsprintf(wstrPath + wstrPathLen, L"\\%s\\", _programName); - hDumpFile = _generateDumpFileAtPath(wstrPath); - } - } - - if (!hDumpFile || hDumpFile == INVALID_HANDLE_VALUE) { - return; - } - - MINIDUMP_EXCEPTION_INFORMATION ExpParam = {0}; - ExpParam.ThreadId = GetCurrentThreadId(); - ExpParam.ExceptionPointers = pExceptionPointers; - ExpParam.ClientPointers = TRUE; - - miniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpWithDataSegs, &ExpParam, NULL, NULL); -} - -LONG CALLBACK _exceptionFilter(EXCEPTION_POINTERS* pExceptionPointers) { - _generateDump(pExceptionPointers); - return _oldWndExceptionFilter ? (*_oldWndExceptionFilter)(pExceptionPointers) : EXCEPTION_CONTINUE_SEARCH; -} - -// see http://www.codeproject.com/Articles/154686/SetUnhandledExceptionFilter-and-the-C-C-Runtime-Li -LPTOP_LEVEL_EXCEPTION_FILTER WINAPI RedirectedSetUnhandledExceptionFilter(_In_opt_ LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter) { - // When the CRT calls SetUnhandledExceptionFilter with NULL parameter - // our handler will not get removed. - _oldWndExceptionFilter = lpTopLevelExceptionFilter; - return 0; -} diff --git a/Telegram/SourceFiles/_other/updater.h b/Telegram/SourceFiles/_other/updater.h deleted file mode 100644 index bf28ab672..000000000 --- a/Telegram/SourceFiles/_other/updater.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -This file is part of Telegram Desktop, -the official desktop version of Telegram messaging app, see https://telegram.org - -Telegram Desktop is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -It is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -In addition, as a special exception, the copyright holders give permission -to link the code of portions of this program with the OpenSSL library. - -Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE -Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org -*/ -#pragma once - -#include -#include - -#pragma warning(push) -#pragma warning(disable:4091) -#include -#include -#pragma warning(pop) - -#include -#include - -#include -#include - -using std::deque; -using std::wstring; - -extern LPTOP_LEVEL_EXCEPTION_FILTER _oldWndExceptionFilter; -LONG CALLBACK _exceptionFilter(EXCEPTION_POINTERS* pExceptionPointers); -LPTOP_LEVEL_EXCEPTION_FILTER WINAPI RedirectedSetUnhandledExceptionFilter(_In_opt_ LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter); - -static int updaterVersion = 1000; -static const WCHAR *updaterVersionStr = L"0.1.0"; diff --git a/Telegram/SourceFiles/_other/updater_linux.cpp b/Telegram/SourceFiles/_other/updater_linux.cpp deleted file mode 100644 index 2e09dd70d..000000000 --- a/Telegram/SourceFiles/_other/updater_linux.cpp +++ /dev/null @@ -1,476 +0,0 @@ -/* -This file is part of Telegram Desktop, -the official desktop version of Telegram messaging app, see https://telegram.org - -Telegram Desktop is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -It is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -In addition, as a special exception, the copyright holders give permission -to link the code of portions of this program with the OpenSSL library. - -Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE -Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org -*/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using std::string; -using std::deque; -using std::cout; - -bool do_mkdir(const char *path) { // from http://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux - struct stat statbuf; - if (stat(path, &statbuf) != 0) { - /* Directory does not exist. EEXIST for race condition */ - if (mkdir(path, S_IRWXU) != 0 && errno != EEXIST) return false; - } else if (!S_ISDIR(statbuf.st_mode)) { - errno = ENOTDIR; - return false; - } - - return true; -} - -bool _debug = false; -string updaterDir; -string updaterName; -string workDir; -string exeName; -string exePath; - -FILE *_logFile = 0; -void openLog() { - if (!_debug || _logFile) return; - - if (!do_mkdir((workDir + "DebugLogs").c_str())) { - return; - } - - time_t timer; - - time(&timer); - struct tm *t = localtime(&timer); - - static const int maxFileLen = 65536; - char logName[maxFileLen]; - sprintf(logName, "%sDebugLogs/%04d%02d%02d_%02d%02d%02d_upd.txt", workDir.c_str(), - t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); - _logFile = fopen(logName, "w"); -} - -void closeLog() { - if (!_logFile) return; - - fclose(_logFile); - _logFile = 0; -} - -void writeLog(const char *format, ...) { - if (!_logFile) { - return; - } - - va_list args; - va_start(args, format); - vfprintf(_logFile, format, args); - fprintf(_logFile, "\n"); - fflush(_logFile); - va_end(args); -} - -bool copyFile(const char *from, const char *to) { - FILE *ffrom = fopen(from, "rb"), *fto = fopen(to, "wb"); - if (!ffrom) { - if (fto) fclose(fto); - return false; - } - if (!fto) { - fclose(ffrom); - return false; - } - static const int BufSize = 65536; - char buf[BufSize]; - while (size_t size = fread(buf, 1, BufSize, ffrom)) { - fwrite(buf, 1, size, fto); - } - - struct stat fst; // from http://stackoverflow.com/questions/5486774/keeping-fileowner-and-permissions-after-copying-file-in-c - //let's say this wont fail since you already worked OK on that fp - if (fstat(fileno(ffrom), &fst) != 0) { - fclose(ffrom); - fclose(fto); - return false; - } - //update to the same uid/gid - if (fchown(fileno(fto), fst.st_uid, fst.st_gid) != 0) { - fclose(ffrom); - fclose(fto); - return false; - } - //update the permissions - if (fchmod(fileno(fto), fst.st_mode) != 0) { - fclose(ffrom); - fclose(fto); - return false; - } - - fclose(ffrom); - fclose(fto); - - return true; -} - -bool remove_directory(const string &path) { // from http://stackoverflow.com/questions/2256945/removing-a-non-empty-directory-programmatically-in-c-or-c - DIR *d = opendir(path.c_str()); - writeLog("Removing dir '%s'", path.c_str()); - - if (!d) { - writeLog("Could not open dir '%s'", path.c_str()); - return (errno == ENOENT); - } - - while (struct dirent *p = readdir(d)) { - /* Skip the names "." and ".." as we don't want to recurse on them. */ - if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue; - - string fname = path + '/' + p->d_name; - struct stat statbuf; - writeLog("Trying to get stat() for '%s'", fname.c_str()); - if (!stat(fname.c_str(), &statbuf)) { - if (S_ISDIR(statbuf.st_mode)) { - if (!remove_directory(fname.c_str())) { - closedir(d); - return false; - } - } else { - writeLog("Unlinking file '%s'", fname.c_str()); - if (unlink(fname.c_str())) { - writeLog("Failed to unlink '%s'", fname.c_str()); - closedir(d); - return false; - } - } - } else { - writeLog("Failed to call stat() on '%s'", fname.c_str()); - } - } - closedir(d); - - writeLog("Finally removing dir '%s'", path.c_str()); - return !rmdir(path.c_str()); -} - -bool mkpath(const char *path) { - int status = 0, pathsize = strlen(path) + 1; - char *copypath = new char[pathsize]; - memcpy(copypath, path, pathsize); - - char *pp = copypath, *sp; - while (status == 0 && (sp = strchr(pp, '/')) != 0) { - if (sp != pp) { - /* Neither root nor double slash in path */ - *sp = '\0'; - if (!do_mkdir(copypath)) { - delete[] copypath; - return false; - } - *sp = '/'; - } - pp = sp + 1; - } - delete[] copypath; - return do_mkdir(path); -} - -bool equal(string a, string b) { - std::transform(a.begin(), a.end(), a.begin(), ::tolower); - std::transform(b.begin(), b.end(), b.begin(), ::tolower); - return a == b; -} - -void delFolder() { - string delPathOld = workDir + "tupdates/ready", delPath = workDir + "tupdates/temp", delFolder = workDir + "tupdates"; - writeLog("Fully clearing old path '%s'..", delPathOld.c_str()); - if (!remove_directory(delPathOld)) { - writeLog("Failed to clear old path! :( New path was used?.."); - } - writeLog("Fully clearing path '%s'..", delPath.c_str()); - if (!remove_directory(delPath)) { - writeLog("Error: failed to clear path! :("); - } - rmdir(delFolder.c_str()); -} - -bool update() { - writeLog("Update started.."); - - string updDir = workDir + "tupdates/temp", readyFilePath = workDir + "tupdates/temp/ready", tdataDir = workDir + "tupdates/temp/tdata"; - { - FILE *readyFile = fopen(readyFilePath.c_str(), "rb"); - if (readyFile) { - fclose(readyFile); - writeLog("Ready file found! Using new path '%s'..", updDir.c_str()); - } else { - updDir = workDir + "tupdates/ready"; // old - tdataDir = workDir + "tupdates/ready/tdata"; - writeLog("Ready file not found! Using old path '%s'..", updDir.c_str()); - } - } - - deque dirs; - dirs.push_back(updDir); - - deque from, to, forcedirs; - - do { - string dir = dirs.front(); - dirs.pop_front(); - - string toDir = exePath; - if (dir.size() > updDir.size() + 1) { - toDir += (dir.substr(updDir.size() + 1) + '/'); - forcedirs.push_back(toDir); - writeLog("Parsing dir '%s' in update tree..", toDir.c_str()); - } - - DIR *d = opendir(dir.c_str()); - if (!d) { - writeLog("Failed to open dir %s", dir.c_str()); - return false; - } - - while (struct dirent *p = readdir(d)) { - /* Skip the names "." and ".." as we don't want to recurse on them. */ - if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue; - - string fname = dir + '/' + p->d_name; - struct stat statbuf; - if (fname.substr(0, tdataDir.size()) == tdataDir && (fname.size() <= tdataDir.size() || fname.at(tdataDir.size()) == '/')) { - writeLog("Skipping 'tdata' path '%s'", fname.c_str()); - } else if (!stat(fname.c_str(), &statbuf)) { - if (S_ISDIR(statbuf.st_mode)) { - dirs.push_back(fname); - writeLog("Added dir '%s' in update tree..", fname.c_str()); - } else { - string tofname = exePath + fname.substr(updDir.size() + 1); - if (equal(tofname, updaterName)) { // bad update - has Updater - delete all dir - writeLog("Error: bad update, has Updater! '%s' equal '%s'", tofname.c_str(), updaterName.c_str()); - delFolder(); - return false; - } else if (equal(tofname, exePath + "Telegram") && exeName != "Telegram") { - string fullBinaryPath = exePath + exeName; - writeLog("Target binary found: '%s', changing to '%s'", tofname.c_str(), fullBinaryPath.c_str()); - tofname = fullBinaryPath; - } - if (fname == readyFilePath) { - writeLog("Skipped ready file '%s'", fname.c_str()); - } else { - from.push_back(fname); - to.push_back(tofname); - writeLog("Added file '%s' to be copied to '%s'", fname.c_str(), tofname.c_str()); - } - } - } else { - writeLog("Could not get stat() for file %s", fname.c_str()); - } - } - closedir(d); - } while (!dirs.empty()); - - for (size_t i = 0; i < forcedirs.size(); ++i) { - string forcedir = forcedirs[i]; - writeLog("Forcing dir '%s'..", forcedir.c_str()); - if (!forcedir.empty() && !mkpath(forcedir.c_str())) { - writeLog("Error: failed to create dir '%s'..", forcedir.c_str()); - delFolder(); - return false; - } - } - - for (size_t i = 0; i < from.size(); ++i) { - string fname = from[i], tofname = to[i]; - writeLog("Copying file '%s' to '%s'..", fname.c_str(), tofname.c_str()); - int copyTries = 0, triesLimit = 30; - do { - if (!copyFile(fname.c_str(), tofname.c_str())) { - ++copyTries; - usleep(100000); - } else { - break; - } - } while (copyTries < triesLimit); - if (copyTries == triesLimit) { - writeLog("Error: failed to copy, asking to retry.."); - delFolder(); - return false; - } - } - - writeLog("Update succeed! Clearing folder.."); - delFolder(); - return true; -} - -string CurrentExecutablePath(int argc, char *argv[]) { - constexpr auto kMaxPath = 1024; - char result[kMaxPath] = { 0 }; - auto count = readlink("/proc/self/exe", result, kMaxPath); - if (count > 0) { - return string(result); - } - - // Fallback to the first command line argument. - return argc ? string(argv[0]) : string(); -} - -int main(int argc, char *argv[]) { - bool needupdate = true, autostart = false, debug = false, tosettings = false, startintray = false, testmode = false; - - char *key = 0, *crashreport = 0; - for (int i = 1; i < argc; ++i) { - if (equal(argv[i], "-noupdate")) { - needupdate = false; - } else if (equal(argv[i], "-autostart")) { - autostart = true; - } else if (equal(argv[i], "-debug")) { - debug = _debug = true; - } else if (equal(argv[i], "-startintray")) { - startintray = true; - } else if (equal(argv[i], "-testmode")) { - testmode = true; - } else if (equal(argv[i], "-tosettings")) { - tosettings = true; - } else if (equal(argv[i], "-key") && ++i < argc) { - key = argv[i]; - } else if (equal(argv[i], "-workpath") && ++i < argc) { - workDir = argv[i]; - } else if (equal(argv[i], "-crashreport") && ++i < argc) { - crashreport = argv[i]; - } else if (equal(argv[i], "-exename") && ++i < argc) { - exeName = argv[i]; - } else if (equal(argv[i], "-exepath") && ++i < argc) { - exePath = argv[i]; - } - } - if (exeName.empty() || exeName.find('/') != string::npos) { - exeName = "Telegram"; - } - openLog(); - - writeLog("Updater started.."); - for (int i = 0; i < argc; ++i) { - writeLog("Argument: '%s'", argv[i]); - } - if (needupdate) writeLog("Need to update!"); - if (autostart) writeLog("From autostart!"); - - updaterName = CurrentExecutablePath(argc, argv); - writeLog("Updater binary full path is: %s", updaterName.c_str()); - if (exePath.empty()) { - writeLog("Executable path is not specified :("); - } else { - writeLog("Executable path: %s", exePath.c_str()); - } - if (updaterName.size() >= 7) { - if (equal(updaterName.substr(updaterName.size() - 7), "Updater")) { - updaterDir = updaterName.substr(0, updaterName.size() - 7); - writeLog("Updater binary dir is: %s", updaterDir.c_str()); - if (exePath.empty()) { - exePath = updaterDir; - writeLog("Using updater binary dir.", exePath.c_str()); - } - if (needupdate) { - if (workDir.empty()) { // old app launched, update prepared in tupdates/ready (not in tupdates/temp) - writeLog("No workdir, trying to figure it out"); - struct passwd *pw = getpwuid(getuid()); - if (pw && pw->pw_dir && strlen(pw->pw_dir)) { - string tryDir = pw->pw_dir + string("/.TelegramDesktop/"); - struct stat statbuf; - writeLog("Trying to use '%s' as workDir, getting stat() for tupdates/ready", tryDir.c_str()); - if (!stat((tryDir + "tupdates/ready").c_str(), &statbuf)) { - writeLog("Stat got"); - if (S_ISDIR(statbuf.st_mode)) { - writeLog("It is directory, using home work dir"); - workDir = tryDir; - } - } - } - if (workDir.empty()) { - workDir = exePath; - - struct stat statbuf; - writeLog("Trying to use current as workDir, getting stat() for tupdates/ready"); - if (!stat("tupdates/ready", &statbuf)) { - writeLog("Stat got"); - if (S_ISDIR(statbuf.st_mode)) { - writeLog("It is directory, using current dir"); - workDir = string(); - } - } - } - } else { - writeLog("Passed workpath is '%s'", workDir.c_str()); - } - update(); - } - } else { - writeLog("Error: bad exe name!"); - } - } else { - writeLog("Error: short exe name!"); - } - - static const int MaxLen = 65536, MaxArgsCount = 128; - - char path[MaxLen] = {0}; - string fullBinaryPath = exePath + exeName; - strcpy(path, fullBinaryPath.c_str()); - - char *args[MaxArgsCount] = {0}, p_noupdate[] = "-noupdate", p_autostart[] = "-autostart", p_debug[] = "-debug", p_tosettings[] = "-tosettings", p_key[] = "-key", p_startintray[] = "-startintray", p_testmode[] = "-testmode"; - int argIndex = 0; - args[argIndex++] = path; - if (crashreport) { - args[argIndex++] = crashreport; - } else { - args[argIndex++] = p_noupdate; - if (autostart) args[argIndex++] = p_autostart; - if (debug) args[argIndex++] = p_debug; - if (startintray) args[argIndex++] = p_startintray; - if (testmode) args[argIndex++] = p_testmode; - if (tosettings) args[argIndex++] = p_tosettings; - if (key) { - args[argIndex++] = p_key; - args[argIndex++] = key; - } - } - pid_t pid = fork(); - switch (pid) { - case -1: writeLog("fork() failed!"); return 1; - case 0: execv(path, args); return 1; - } - - writeLog("Executed Telegram, closing log and quitting.."); - closeLog(); - - return 0; -} diff --git a/Telegram/SourceFiles/_other/updater_osx.m b/Telegram/SourceFiles/_other/updater_osx.m deleted file mode 100644 index b2b9d0b03..000000000 --- a/Telegram/SourceFiles/_other/updater_osx.m +++ /dev/null @@ -1,272 +0,0 @@ -/* -This file is part of Telegram Desktop, -the official desktop version of Telegram messaging app, see https://telegram.org - -Telegram Desktop is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -It is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -In addition, as a special exception, the copyright holders give permission -to link the code of portions of this program with the OpenSSL library. - -Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE -Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org -*/ -#import - -NSString *appName = @"Telegram.app"; -NSString *appDir = nil; -NSString *workDir = nil; -NSString *crashReportArg = nil; - -#ifdef _DEBUG -BOOL _debug = YES; -#else -BOOL _debug = NO; -#endif - -NSFileHandle *_logFile = nil; -void openLog() { - if (!_debug || _logFile) return; - NSString *logDir = [workDir stringByAppendingString:@"DebugLogs"]; - if (![[NSFileManager defaultManager] createDirectoryAtPath:logDir withIntermediateDirectories:YES attributes:nil error:nil]) { - return; - } - - NSDateFormatter *fmt = [[NSDateFormatter alloc] initWithDateFormat:@"DebugLogs/%Y%m%d_%H%M%S_upd.txt" allowNaturalLanguage:NO]; - NSString *logPath = [workDir stringByAppendingString:[fmt stringFromDate:[NSDate date]]]; - [[NSFileManager defaultManager] createFileAtPath:logPath contents:nil attributes:nil]; - _logFile = [NSFileHandle fileHandleForWritingAtPath:logPath]; -} - -void closeLog() { - if (!_logFile) return; - - [_logFile closeFile]; -} - -void writeLog(NSString *msg) { - if (!_logFile) return; - - [_logFile writeData:[[msg stringByAppendingString:@"\n"] dataUsingEncoding:NSUTF8StringEncoding]]; - [_logFile synchronizeFile]; -} - -void delFolder() { - writeLog([@"Fully clearing old path: " stringByAppendingString:[workDir stringByAppendingString:@"tupdates/ready"]]); - if (![[NSFileManager defaultManager] removeItemAtPath:[workDir stringByAppendingString:@"tupdates/ready"] error:nil]) { - writeLog(@"Failed to clear old path! :( New path was used?.."); - } - writeLog([@"Fully clearing new path: " stringByAppendingString:[workDir stringByAppendingString:@"tupdates/temp"]]); - if (![[NSFileManager defaultManager] removeItemAtPath:[workDir stringByAppendingString:@"tupdates/temp"] error:nil]) { - writeLog(@"Error: failed to clear new path! :("); - } - rmdir([[workDir stringByAppendingString:@"tupdates"] fileSystemRepresentation]); -} - -int main(int argc, const char * argv[]) { - NSString *path = [[NSBundle mainBundle] bundlePath]; - if (!path) { - return -1; - } - NSRange range = [path rangeOfString:@".app/" options:NSBackwardsSearch]; - if (range.location == NSNotFound) { - return -1; - } - path = [path substringToIndex:range.location > 0 ? range.location : 0]; - - range = [path rangeOfString:@"/" options:NSBackwardsSearch]; - NSString *appRealName = (range.location == NSNotFound) ? path : [path substringFromIndex:range.location + 1]; - appRealName = [[NSArray arrayWithObjects:appRealName, @".app", nil] componentsJoinedByString:@""]; - appDir = (range.location == NSNotFound) ? @"" : [path substringToIndex:range.location + 1]; - NSString *appDirFull = [appDir stringByAppendingString:appRealName]; - - openLog(); - pid_t procId = 0; - BOOL update = YES, toSettings = NO, autoStart = NO, startInTray = NO, testMode = NO; - NSString *key = nil; - for (int i = 0; i < argc; ++i) { - if ([@"-workpath" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) { - if (++i < argc) { - workDir = [NSString stringWithUTF8String:argv[i]]; - } - } else if ([@"-procid" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) { - if (++i < argc) { - NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; - [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; - procId = [[formatter numberFromString:[NSString stringWithUTF8String:argv[i]]] intValue]; - } - } else if ([@"-crashreport" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) { - if (++i < argc) { - crashReportArg = [NSString stringWithUTF8String:argv[i]]; - } - } else if ([@"-noupdate" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) { - update = NO; - } else if ([@"-tosettings" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) { - toSettings = YES; - } else if ([@"-autostart" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) { - autoStart = YES; - } else if ([@"-debug" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) { - _debug = YES; - } else if ([@"-startintray" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) { - startInTray = YES; - } else if ([@"-testmode" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) { - testMode = YES; - } else if ([@"-key" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) { - if (++i < argc) key = [NSString stringWithUTF8String:argv[i]]; - } - } - if (!workDir) workDir = appDir; - openLog(); - NSMutableArray *argsArr = [[NSMutableArray alloc] initWithCapacity:argc]; - for (int i = 0; i < argc; ++i) { - [argsArr addObject:[NSString stringWithUTF8String:argv[i]]]; - } - writeLog([[NSArray arrayWithObjects:@"Arguments: '", [argsArr componentsJoinedByString:@"' '"], @"'..", nil] componentsJoinedByString:@""]); - if (key) writeLog([@"Key: " stringByAppendingString:key]); - if (toSettings) writeLog(@"To Settings!"); - - if (procId) { - NSRunningApplication *app = [NSRunningApplication runningApplicationWithProcessIdentifier:procId]; - for (int i = 0; i < 5 && app != nil && ![app isTerminated]; ++i) { - usleep(200000); - app = [NSRunningApplication runningApplicationWithProcessIdentifier:procId]; - } - if (app) [app forceTerminate]; - app = [NSRunningApplication runningApplicationWithProcessIdentifier:procId]; - for (int i = 0; i < 5 && app != nil && ![app isTerminated]; ++i) { - usleep(200000); - app = [NSRunningApplication runningApplicationWithProcessIdentifier:procId]; - } - } - - if (update) { - NSFileManager *fileManager = [NSFileManager defaultManager]; - NSString *readyFilePath = [workDir stringByAppendingString:@"tupdates/temp/ready"]; - NSString *srcDir = [workDir stringByAppendingString:@"tupdates/temp/"], *srcEnum = [workDir stringByAppendingString:@"tupdates/temp"]; - if ([fileManager fileExistsAtPath:readyFilePath]) { - writeLog([@"Ready file found! Using new path: " stringByAppendingString: srcEnum]); - } else { - srcDir = [workDir stringByAppendingString:@"tupdates/ready/"]; // old - srcEnum = [workDir stringByAppendingString:@"tupdates/ready"]; - writeLog([@"Ready file not found! Using old path: " stringByAppendingString: srcEnum]); - } - - writeLog([@"Starting update files iteration, path: " stringByAppendingString: srcEnum]); - - // Take the Updater (this currently running binary) from the place where it was placed by Telegram - // and copy it to the folder with the new version of the app (ready), - // so it won't be deleted when we will clear the "Telegram.app/Contents" folder. - NSString *oldVersionUpdaterPath = [appDirFull stringByAppendingString: @"/Contents/Frameworks/Updater" ]; - NSString *newVersionUpdaterPath = [srcEnum stringByAppendingString:[[NSArray arrayWithObjects:@"/", appName, @"/Contents/Frameworks/Updater", nil] componentsJoinedByString:@""]]; - writeLog([[NSArray arrayWithObjects: @"Copying Updater from old path ", oldVersionUpdaterPath, @" to new path ", newVersionUpdaterPath, nil] componentsJoinedByString:@""]); - if (![fileManager fileExistsAtPath:newVersionUpdaterPath]) { - if (![fileManager copyItemAtPath:oldVersionUpdaterPath toPath:newVersionUpdaterPath error:nil]) { - writeLog([[NSArray arrayWithObjects: @"Failed to copy file from ", oldVersionUpdaterPath, @" to ", newVersionUpdaterPath, nil] componentsJoinedByString:@""]); - delFolder(); - return -1; - } - } - - - NSString *contentsPath = [appDirFull stringByAppendingString: @"/Contents"]; - writeLog([[NSArray arrayWithObjects: @"Clearing dir ", contentsPath, nil] componentsJoinedByString:@""]); - if (![fileManager removeItemAtPath:contentsPath error:nil]) { - writeLog([@"Failed to clear path for directory " stringByAppendingString:contentsPath]); - delFolder(); - return -1; - } - - NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey]; - NSDirectoryEnumerator *enumerator = [fileManager - enumeratorAtURL:[NSURL fileURLWithPath:srcEnum] - includingPropertiesForKeys:keys - options:0 - errorHandler:^(NSURL *url, NSError *error) { - writeLog([[[@"Error in enumerating " stringByAppendingString:[url absoluteString]] stringByAppendingString: @" error is: "] stringByAppendingString: [error description]]); - return NO; - }]; - for (NSURL *url in enumerator) { - NSString *srcPath = [url path]; - writeLog([@"Handling file " stringByAppendingString:srcPath]); - NSRange r = [srcPath rangeOfString:srcDir]; - if (r.location != 0) { - writeLog([@"Bad file found, no base path " stringByAppendingString:srcPath]); - delFolder(); - break; - } - NSString *pathPart = [srcPath substringFromIndex:r.length]; - r = [pathPart rangeOfString:appName]; - if (r.location != 0) { - writeLog([@"Skipping not app file " stringByAppendingString:srcPath]); - continue; - } - NSString *dstPath = [appDirFull stringByAppendingString:[pathPart substringFromIndex:r.length]]; - NSError *error; - NSNumber *isDirectory = nil; - if (![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) { - writeLog([@"Failed to get IsDirectory for file " stringByAppendingString:[url path]]); - delFolder(); - break; - } - if ([isDirectory boolValue]) { - writeLog([[NSArray arrayWithObjects: @"Copying dir ", srcPath, @" to ", dstPath, nil] componentsJoinedByString:@""]); - if (![fileManager createDirectoryAtPath:dstPath withIntermediateDirectories:YES attributes:nil error:nil]) { - writeLog([@"Failed to force path for directory " stringByAppendingString:dstPath]); - delFolder(); - break; - } - } else if ([srcPath isEqualToString:readyFilePath]) { - writeLog([[NSArray arrayWithObjects: @"Skipping ready file ", srcPath, nil] componentsJoinedByString:@""]); - } else if ([fileManager fileExistsAtPath:dstPath]) { - if (![[NSData dataWithContentsOfFile:srcPath] writeToFile:dstPath atomically:YES]) { - writeLog([@"Failed to edit file " stringByAppendingString:dstPath]); - delFolder(); - break; - } - } else { - if (![fileManager copyItemAtPath:srcPath toPath:dstPath error:nil]) { - writeLog([@"Failed to copy file to " stringByAppendingString:dstPath]); - delFolder(); - break; - } - } - } - delFolder(); - } - - NSString *appPath = [[NSArray arrayWithObjects:appDir, appRealName, nil] componentsJoinedByString:@""]; - NSMutableArray *args = [[NSMutableArray alloc] initWithObjects: crashReportArg ? crashReportArg : @"-noupdate", nil]; - if (!crashReportArg) { - if (toSettings) [args addObject:@"-tosettings"]; - if (_debug) [args addObject:@"-debug"]; - if (startInTray) [args addObject:@"-startintray"]; - if (testMode) [args addObject:@"-testmode"]; - if (autoStart) [args addObject:@"-autostart"]; - if (key) { - [args addObject:@"-key"]; - [args addObject:key]; - } - } - writeLog([[NSArray arrayWithObjects:@"Running application '", appPath, @"' with args '", [args componentsJoinedByString:@"' '"], @"'..", nil] componentsJoinedByString:@""]); - NSError *error = nil; - NSRunningApplication *result = [[NSWorkspace sharedWorkspace] - launchApplicationAtURL:[NSURL fileURLWithPath:appPath] - options:NSWorkspaceLaunchDefault - configuration:[NSDictionary - dictionaryWithObject:args - forKey:NSWorkspaceLaunchConfigurationArguments] - error:&error]; - if (!result) { - writeLog([@"Could not run application, error: " stringByAppendingString:error ? [error localizedDescription] : @"(nil)"]); - } - closeLog(); - return result ? 0 : -1; -} - diff --git a/Telegram/SourceFiles/apiwrap.cpp b/Telegram/SourceFiles/apiwrap.cpp index 72dc4655a..0ccb53482 100644 --- a/Telegram/SourceFiles/apiwrap.cpp +++ b/Telegram/SourceFiles/apiwrap.cpp @@ -121,7 +121,7 @@ void ApiWrap::addLocalChangelogs(int oldAppVersion) { } } -void ApiWrap::applyUpdates(const MTPUpdates &updates, uint64 sentMessageRandomId) { +void ApiWrap::applyUpdates(const MTPUpdates &updates, uint64_t sentMessageRandomId) { App::main()->feedUpdates(updates, sentMessageRandomId); } @@ -796,7 +796,7 @@ void ApiWrap::unblockParticipant(PeerData *peer, UserData *user) { } } -void ApiWrap::scheduleStickerSetRequest(uint64 setId, uint64 access) { +void ApiWrap::scheduleStickerSetRequest(uint64_t setId, uint64_t access) { if (!_stickerSetRequests.contains(setId)) { _stickerSetRequests.insert(setId, qMakePair(access, 0)); } @@ -1274,7 +1274,7 @@ PeerData *ApiWrap::notifySettingReceived(MTPInputNotifyPeer notifyPeer, const MT return requestedPeer; } -void ApiWrap::gotStickerSet(uint64 setId, const MTPmessages_StickerSet &result) { +void ApiWrap::gotStickerSet(uint64_t setId, const MTPmessages_StickerSet &result) { _stickerSetRequests.remove(setId); Stickers::FeedSetFull(result); } @@ -1302,13 +1302,13 @@ void ApiWrap::clearWebPageRequests() { void ApiWrap::resolveWebPages() { auto ids = QVector(); // temp_req_id = -1 - using IndexAndMessageIds = QPair>; + using IndexAndMessageIds = QPair>; using MessageIdsByChannel = QMap; MessageIdsByChannel idsByChannel; // temp_req_id = -index - 2 auto &items = App::webPageItems(); ids.reserve(_webPagesPending.size()); - int32 t = unixtime(), m = INT_MAX; + int32_t t = unixtime(), m = INT_MAX; for (auto i = _webPagesPending.begin(); i != _webPagesPending.cend(); ++i) { if (i.value() > 0) continue; if (i.key()->pendingTill <= t) { @@ -1405,13 +1405,13 @@ void ApiWrap::gotWebPages(ChannelData *channel, const MTPmessages_Messages &msgs } if (!v) return; - QMap msgsIds; // copied from feedMsgs - for (int32 i = 0, l = v->size(); i < l; ++i) { + QMap msgsIds; // copied from feedMsgs + for (int32_t i = 0, l = v->size(); i < l; ++i) { const auto &msg(v->at(i)); switch (msg.type()) { - case mtpc_message: msgsIds.insert((uint64(uint32(msg.c_message().vid.v)) << 32) | uint64(i), i); break; - case mtpc_messageEmpty: msgsIds.insert((uint64(uint32(msg.c_messageEmpty().vid.v)) << 32) | uint64(i), i); break; - case mtpc_messageService: msgsIds.insert((uint64(uint32(msg.c_messageService().vid.v)) << 32) | uint64(i), i); break; + case mtpc_message: msgsIds.insert((uint64_t(uint32_t(msg.c_message().vid.v)) << 32) | uint64_t(i), i); break; + case mtpc_messageEmpty: msgsIds.insert((uint64_t(uint32_t(msg.c_messageEmpty().vid.v)) << 32) | uint64_t(i), i); break; + case mtpc_messageService: msgsIds.insert((uint64_t(uint32_t(msg.c_messageService().vid.v)) << 32) | uint64_t(i), i); break; } } diff --git a/Telegram/SourceFiles/apiwrap.h b/Telegram/SourceFiles/apiwrap.h index 7b7a94b8f..790f5dc31 100644 --- a/Telegram/SourceFiles/apiwrap.h +++ b/Telegram/SourceFiles/apiwrap.h @@ -21,6 +21,9 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #pragma once #include "base/timer.h" +#include +#include "mtproto/rpc_sender.h" +#include "mtproto/core_types.h" #include "core/single_timer.h" #include "mtproto/sender.h" #include "base/flat_map.h" @@ -45,7 +48,7 @@ public: ApiWrap(not_null session); void start(); - void applyUpdates(const MTPUpdates &updates, uint64 sentMessageRandomId = 0); + void applyUpdates(const MTPUpdates &updates, uint64_t sentMessageRandomId = 0); using RequestMessageDataCallback = base::lambda; void requestMessageData(ChannelData *channel, MsgId msgId, RequestMessageDataCallback callback); @@ -68,7 +71,7 @@ public: void clearWebPageRequest(WebPageData *page); void clearWebPageRequests(); - void scheduleStickerSetRequest(uint64 setId, uint64 access); + void scheduleStickerSetRequest(uint64_t setId, uint64_t access); void requestStickerSets(); void saveStickerSets(const Stickers::Order &localOrder, const Stickers::Order &localRemoved); void updateStickers(); @@ -136,7 +139,7 @@ private: void lastParticipantsDone(ChannelData *peer, const MTPchannels_ChannelParticipants &result, mtpRequestId req); void resolveWebPages(); void gotWebPages(ChannelData *channel, const MTPmessages_Messages &result, mtpRequestId req); - void gotStickerSet(uint64 setId, const MTPmessages_StickerSet &result); + void gotStickerSet(uint64_t setId, const MTPmessages_StickerSet &result); PeerData *notifySettingReceived(MTPInputNotifyPeer peer, const MTPPeerNotifySettings &settings); @@ -177,7 +180,7 @@ private: QMap _webPagesPending; base::Timer _webPagesTimer; - QMap > _stickerSetRequests; + QMap > _stickerSetRequests; QMap _channelAmInRequests; QMap _blockRequests; diff --git a/Telegram/SourceFiles/app.cpp b/Telegram/SourceFiles/app.cpp index 3d4402b11..cc8b6eb31 100644 --- a/Telegram/SourceFiles/app.cpp +++ b/Telegram/SourceFiles/app.cpp @@ -91,10 +91,10 @@ namespace { using ChannelMsgsData = QMap; ChannelMsgsData channelMsgsData; - using RandomData = QMap; + using RandomData = QMap; RandomData randomData; - using SentData = QMap>; + using SentData = QMap>; SentData sentData; HistoryItem *hoveredItem = nullptr, @@ -111,7 +111,7 @@ namespace { QPixmap p[4]; }; QVector corners; - using CornersMap = QMap; + using CornersMap = QMap; CornersMap cornersMap; QImage cornersMaskLarge[4], cornersMaskSmall[4]; @@ -119,7 +119,7 @@ namespace { EmojiImagesMap MainEmojiMap; QMap OtherEmojiMap; - int32 serviceImageCacheSize = 0; + int32_t serviceImageCacheSize = 0; using LastPhotosList = QLinkedList; LastPhotosList lastPhotos; @@ -145,8 +145,8 @@ namespace App { QString result; result.reserve(number.size() + groups.size() + 1); result.append('+'); - int32 sum = 0; - for (int32 i = 0, l = groups.size(); i < l; ++i) { + int32_t sum = 0; + for (int32_t i = 0, l = groups.size(); i < l; ++i) { result.append(number.midRef(sum, groups.at(i))); sum += groups.at(i); if (sum < number.size()) result.append(' '); @@ -227,17 +227,17 @@ namespace { case -2: { QDate yesterday(date(now).date()); - return int32(QDateTime(yesterday.addDays(-3)).toTime_t()) + (unixtime() - myunixtime()); + return int32_t(QDateTime(yesterday.addDays(-3)).toTime_t()) + (unixtime() - myunixtime()); } break; case -3: { QDate weekago(date(now).date()); - return int32(QDateTime(weekago.addDays(-7)).toTime_t()) + (unixtime() - myunixtime()); + return int32_t(QDateTime(weekago.addDays(-7)).toTime_t()) + (unixtime() - myunixtime()); } break; case -4: { QDate monthago(date(now).date()); - return int32(QDateTime(monthago.addDays(-30)).toTime_t()) + (unixtime() - myunixtime()); + return int32_t(QDateTime(monthago.addDays(-30)).toTime_t()) + (unixtime() - myunixtime()); } break; } return -online; @@ -245,14 +245,14 @@ namespace { return online; } - int32 onlineWillChangeIn(UserData *user, TimeId now) { + int32_t onlineWillChangeIn(UserData *user, TimeId now) { if (isServiceUser(user->id) || user->botInfo) { return 86400; } return onlineWillChangeIn(user->onlineTill, now); } - int32 onlineWillChangeIn(TimeId online, TimeId now) { + int32_t onlineWillChangeIn(TimeId online, TimeId now) { if (online <= 0) { if (-online > now) return -online - now; return 86400; @@ -260,11 +260,11 @@ namespace { if (online > now) { return online - now; } - int32 minutes = (now - online) / 60; + int32_t minutes = (now - online) / 60; if (minutes < 60) { return (minutes + 1) * 60 - (now - online); } - int32 hours = (now - online) / 3600; + int32_t hours = (now - online) / 3600; if (hours < 12) { return (hours + 1) * 3600 - (now - online); } @@ -307,13 +307,13 @@ namespace { } return lng_status_lastseen_date_time(lt_date, dOnline.date().toString(qsl("dd.MM.yy")), lt_time, dOnline.time().toString(cTimeFormat())); } - int32 minutes = (now - online) / 60; + int32_t minutes = (now - online) / 60; if (!minutes) { return lang(lng_status_lastseen_now); } else if (minutes < 60) { return lng_status_lastseen_minutes(lt_count, minutes); } - int32 hours = (now - online) / 3600; + int32_t hours = (now - online) / 3600; if (hours < 12) { return lng_status_lastseen_hours(lt_count, hours); } @@ -790,12 +790,12 @@ namespace { chat->version = d.vversion.v; auto &v = d.vparticipants.v; chat->count = v.size(); - int32 pversion = chat->participants.isEmpty() ? 1 : (chat->participants.begin().value() + 1); + int32_t pversion = chat->participants.isEmpty() ? 1 : (chat->participants.begin().value() + 1); chat->invitedByMe.clear(); chat->admins.clear(); chat->flags &= ~MTPDchat::Flag::f_admin; for (auto i = v.cbegin(), e = v.cend(); i != e; ++i) { - int32 uid = 0, inviter = 0; + int32_t uid = 0, inviter = 0; switch (i->type()) { case mtpc_chatParticipantCreator: { const auto &p(i->c_chatParticipantCreator()); @@ -835,7 +835,7 @@ namespace { if (!chat->participants.isEmpty()) { History *h = App::historyLoaded(chat->id); bool found = !h || !h->lastKeyboardFrom; - int32 botStatus = -1; + int32_t botStatus = -1; for (auto i = chat->participants.begin(), e = chat->participants.end(); i != e;) { if (i.value() < pversion) { i = chat->participants.erase(i); @@ -934,7 +934,7 @@ namespace { } } if (chat->botStatus > 0 && user->botInfo) { - int32 botStatus = -1; + int32_t botStatus = -1; for (auto j = chat->participants.cbegin(), e = chat->participants.cend(); j != e; ++j) { if (j.key()->botInfo) { if (true || botStatus > 0/* || !j.key()->botInfo->readsAllHistory*/) { @@ -1060,7 +1060,7 @@ namespace { void addSavedGif(DocumentData *doc) { SavedGifs &saved(cRefSavedGifs()); - int32 index = saved.indexOf(doc); + int32_t index = saved.indexOf(doc); if (index) { if (index > 0) saved.remove(index); saved.push_front(doc); @@ -1086,8 +1086,8 @@ namespace { } void feedMsgs(const QVector &msgs, NewMessageType type) { - QMap msgsIds; - for (int32 i = 0, l = msgs.size(); i < l; ++i) { + QMap msgsIds; + for (int32_t i = 0, l = msgs.size(); i < l; ++i) { const auto &msg(msgs.at(i)); switch (msg.type()) { case mtpc_message: { @@ -1100,14 +1100,14 @@ namespace { } } if (needToAdd) { - msgsIds.insert((uint64(uint32(d.vid.v)) << 32) | uint64(i), i); + msgsIds.insert((uint64_t(uint32_t(d.vid.v)) << 32) | uint64_t(i), i); } } break; - case mtpc_messageEmpty: msgsIds.insert((uint64(uint32(msg.c_messageEmpty().vid.v)) << 32) | uint64(i), i); break; - case mtpc_messageService: msgsIds.insert((uint64(uint32(msg.c_messageService().vid.v)) << 32) | uint64(i), i); break; + case mtpc_messageEmpty: msgsIds.insert((uint64_t(uint32_t(msg.c_messageEmpty().vid.v)) << 32) | uint64_t(i), i); break; + case mtpc_messageService: msgsIds.insert((uint64_t(uint32_t(msg.c_messageService().vid.v)) << 32) | uint64_t(i), i); break; } } - for (QMap::const_iterator i = msgsIds.cbegin(), e = msgsIds.cend(); i != e; ++i) { + for (QMap::const_iterator i = msgsIds.cbegin(), e = msgsIds.cend(); i != e; ++i) { histories().addNewMessage(msgs.at(i.value()), type); } } @@ -1140,7 +1140,7 @@ namespace { return ImagePtr(); } - StorageImageLocation imageLocation(int32 w, int32 h, const MTPFileLocation &loc) { + StorageImageLocation imageLocation(int32_t w, int32_t h, const MTPFileLocation &loc) { if (loc.type() == mtpc_fileLocation) { const auto &l(loc.c_fileLocation()); return StorageImageLocation(w, h, l.vdc_id.v, l.vvolume_id.v, l.vlocal_id.v, l.vsecret.v); @@ -1279,9 +1279,9 @@ namespace { PhotoData *feedPhoto(const MTPPhoto &photo, const PreparedPhotoThumbs &thumbs) { const QPixmap *thumb = 0, *medium = 0, *full = 0; - int32 thumbLevel = -1, mediumLevel = -1, fullLevel = -1; + int32_t thumbLevel = -1, mediumLevel = -1, fullLevel = -1; for (PreparedPhotoThumbs::const_iterator i = thumbs.cbegin(), e = thumbs.cend(); i != e; ++i) { - int32 newThumbLevel = -1, newMediumLevel = -1, newFullLevel = -1; + int32_t newThumbLevel = -1, newMediumLevel = -1, newFullLevel = -1; switch (i.key()) { case 's': newThumbLevel = 0; newMediumLevel = 5; newFullLevel = 4; break; // box 100x100 case 'm': newThumbLevel = 2; newMediumLevel = 0; newFullLevel = 3; break; // box 320x320 @@ -1325,7 +1325,7 @@ namespace { PhotoData *feedPhoto(const MTPDphoto &photo, PhotoData *convert) { auto &sizes = photo.vsizes.v; const MTPPhotoSize *thumb = 0, *medium = 0, *full = 0; - int32 thumbLevel = -1, mediumLevel = -1, fullLevel = -1; + int32_t thumbLevel = -1, mediumLevel = -1, fullLevel = -1; for (QVector::const_iterator i = sizes.cbegin(), e = sizes.cend(); i != e; ++i) { char size = 0; switch (i->type()) { @@ -1341,7 +1341,7 @@ namespace { } if (!size) continue; - int32 newThumbLevel = -1, newMediumLevel = -1, newFullLevel = -1; + int32_t newThumbLevel = -1, newMediumLevel = -1, newFullLevel = -1; switch (size) { case 's': newThumbLevel = 0; newMediumLevel = 5; newFullLevel = 4; break; // box 100x100 case 'm': newThumbLevel = 2; newMediumLevel = 0; newFullLevel = 3; break; // box 320x320 @@ -1468,6 +1468,7 @@ namespace { return nullptr; } } break; + case PeerData::NotLoaded: break; } return i.value(); } @@ -1514,7 +1515,7 @@ namespace { return i.value(); } - PhotoData *photoSet(const PhotoId &photo, PhotoData *convert, const uint64 &access, int32 date, const ImagePtr &thumb, const ImagePtr &medium, const ImagePtr &full) { + PhotoData *photoSet(const PhotoId &photo, PhotoData *convert, const uint64_t &access, int32_t date, const ImagePtr &thumb, const ImagePtr &medium, const ImagePtr &full) { if (convert) { if (convert->id != photo) { PhotosData::iterator i = ::photosData.find(convert->id); @@ -1575,7 +1576,7 @@ namespace { return i.value(); } - DocumentData *documentSet(const DocumentId &document, DocumentData *convert, const uint64 &access, int32 version, int32 date, const QVector &attributes, const QString &mime, const ImagePtr &thumb, int32 dc, int32 size, const StorageImageLocation &thumbLocation) { + DocumentData *documentSet(const DocumentId &document, DocumentData *convert, const uint64_t &access, int32_t version, int32_t date, const QVector &attributes, const QString &mime, const ImagePtr &thumb, int32_t dc, int32_t size, const StorageImageLocation &thumbLocation) { bool versionChanged = false; bool sentSticker = false; if (convert) { @@ -1697,7 +1698,7 @@ namespace { return i.value(); } - WebPageData *webPageSet(const WebPageId &webPage, WebPageData *convert, const QString &type, const QString &url, const QString &displayUrl, const QString &siteName, const QString &title, const TextWithEntities &description, PhotoData *photo, DocumentData *document, int32 duration, const QString &author, int32 pendingTill) { + WebPageData *webPageSet(const WebPageId &webPage, WebPageData *convert, const QString &type, const QString &url, const QString &displayUrl, const QString &siteName, const QString &title, const TextWithEntities &description, PhotoData *photo, DocumentData *document, int32_t duration, const QString &author, int32_t pendingTill) { if (convert) { if (convert->id != webPage) { auto i = webPagesData.find(convert->id); @@ -1769,7 +1770,7 @@ namespace { return i.value(); } - GameData *gameSet(const GameId &game, GameData *convert, const uint64 &accessHash, const QString &shortName, const QString &title, const QString &description, PhotoData *photo, DocumentData *document) { + GameData *gameSet(const GameId &game, GameData *convert, const uint64_t &accessHash, const QString &shortName, const QString &title, const QString &description, PhotoData *photo, DocumentData *document) { if (convert) { if (convert->id != game) { auto i = gamesData.find(convert->id); @@ -1862,7 +1863,7 @@ namespace { return ::histories.findOrInsert(peer); } - History *historyFromDialog(const PeerId &peer, int32 unreadCnt, int32 maxInboxRead, int32 maxOutboxRead) { + History *historyFromDialog(const PeerId &peer, int32_t unreadCnt, int32_t maxInboxRead, int32_t maxOutboxRead) { return ::histories.findOrInsert(peer, unreadCnt, maxInboxRead, maxOutboxRead); } @@ -2056,15 +2057,15 @@ namespace { } } - void historyRegRandom(uint64 randomId, const FullMsgId &itemId) { + void historyRegRandom(uint64_t randomId, const FullMsgId &itemId) { randomData.insert(randomId, itemId); } - void historyUnregRandom(uint64 randomId) { + void historyUnregRandom(uint64_t randomId) { randomData.remove(randomId); } - FullMsgId histItemByRandom(uint64 randomId) { + FullMsgId histItemByRandom(uint64_t randomId) { RandomData::const_iterator i = randomData.constFind(randomId); if (i != randomData.cend()) { return i.value(); @@ -2072,23 +2073,23 @@ namespace { return FullMsgId(); } - void historyRegSentData(uint64 randomId, const PeerId &peerId, const QString &text) { + void historyRegSentData(uint64_t randomId, const PeerId &peerId, const QString &text) { sentData.insert(randomId, qMakePair(peerId, text)); } - void historyUnregSentData(uint64 randomId) { + void historyUnregSentData(uint64_t randomId) { sentData.remove(randomId); } - void histSentDataByItem(uint64 randomId, PeerId &peerId, QString &text) { + void histSentDataByItem(uint64_t randomId, PeerId &peerId, QString &text) { QPair d = sentData.value(randomId); peerId = d.first; text = d.second; } - void prepareCorners(RoundCorners index, int32 radius, const QBrush &brush, const style::color *shadow = nullptr, QImage *cors = nullptr) { + void prepareCorners(RoundCorners index, int32_t radius, const QBrush &brush, const style::color *shadow = nullptr, QImage *cors = nullptr) { Expects(::corners.size() > index); - int32 r = radius * cIntRetinaFactor(), s = st::msgShadow * cIntRetinaFactor(); + int32_t r = radius * cIntRetinaFactor(), s = st::msgShadow * cIntRetinaFactor(); QImage rect(r * 3, r * 3 + (shadow ? s : 0), QImage::Format_ARGB32_Premultiplied), localCors[4]; { Painter p(&rect); @@ -2335,7 +2336,7 @@ namespace { return *::emojiLarge; } - const QPixmap &emojiSingle(EmojiPtr emoji, int32 fontHeight) { + const QPixmap &emojiSingle(EmojiPtr emoji, int32_t fontHeight) { auto &map = (fontHeight == st::msgFont->height) ? MainEmojiMap : OtherEmojiMap[fontHeight]; auto i = map.constFind(emoji->index()); if (i == map.cend()) { @@ -2352,7 +2353,7 @@ namespace { } void checkImageCacheSize() { - int64 nowImageCacheSize = imageCacheSize(); + int64_t nowImageCacheSize = imageCacheSize(); if (nowImageCacheSize > serviceImageCacheSize + MemoryForImageCache) { App::forgetMedia(); serviceImageCacheSize = imageCacheSize(); @@ -2392,17 +2393,8 @@ namespace { } void restart() { -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - bool updateReady = (Sandbox::updatingState() == Application::UpdatingReady); -#else // !TDESKTOP_DISABLE_AUTOUPDATE - bool updateReady = false; -#endif // else for !TDESKTOP_DISABLE_AUTOUPDATE - if (updateReady) { - cSetRestartingUpdate(true); - } else { - cSetRestarting(true); - cSetRestartingToSettings(true); - } + cSetRestarting(true); + cSetRestartingToSettings(true); App::quit(); } @@ -2532,7 +2524,7 @@ namespace { return ::gameItems; } - void regSharedContactItem(int32 userId, HistoryItem *item) { + void regSharedContactItem(int32_t userId, HistoryItem *item) { auto user = App::userLoaded(userId); auto canShareThisContact = user ? user->canShareThisContact() : false; ::sharedContactItems[userId].insert(item); @@ -2541,7 +2533,7 @@ namespace { } } - void unregSharedContactItem(int32 userId, HistoryItem *item) { + void unregSharedContactItem(int32_t userId, HistoryItem *item) { auto user = App::userLoaded(userId); auto canShareThisContact = user ? user->canShareThisContact() : false; ::sharedContactItems[userId].remove(item); @@ -2575,7 +2567,7 @@ namespace { } } - QString phoneFromSharedContact(int32 userId) { + QString phoneFromSharedContact(int32_t userId) { auto i = ::sharedContactItems.constFind(userId); if (i != ::sharedContactItems.cend() && !i->isEmpty()) { if (auto media = (*i->cbegin())->getMedia()) { @@ -2587,7 +2579,7 @@ namespace { return QString(); } - void regMuted(PeerData *peer, int32 changeIn) { + void regMuted(PeerData *peer, int32_t changeIn) { ::mutedPeers.insert(peer, true); if (App::main()) App::main()->updateMutedIn(changeIn); } @@ -2597,9 +2589,9 @@ namespace { } void updateMuted() { - int32 changeInMin = 0; + int32_t changeInMin = 0; for (MutedPeers::iterator i = ::mutedPeers.begin(); i != ::mutedPeers.end();) { - int32 changeIn = 0; + int32_t changeIn = 0; History *h = App::history(i.key()->id); if (isNotifyMuted(i.key()->notify, &changeIn)) { h->setMute(true); @@ -2694,7 +2686,7 @@ namespace { return ::cornersMaskSmall; } - void roundRect(Painter &p, int32 x, int32 y, int32 w, int32 h, style::color bg, const CornersPixmaps &corner, const style::color *shadow, RectParts parts) { + void roundRect(Painter &p, int32_t x, int32_t y, int32_t w, int32_t h, style::color bg, const CornersPixmaps &corner, const style::color *shadow, RectParts parts) { auto cornerWidth = corner.p[0].width() / cIntRetinaFactor(); auto cornerHeight = corner.p[0].height() / cIntRetinaFactor(); if (w < 2 * cornerWidth || h < 2 * cornerHeight) return; @@ -2738,11 +2730,11 @@ namespace { } } - void roundRect(Painter &p, int32 x, int32 y, int32 w, int32 h, style::color bg, RoundCorners index, const style::color *shadow, RectParts parts) { + void roundRect(Painter &p, int32_t x, int32_t y, int32_t w, int32_t h, style::color bg, RoundCorners index, const style::color *shadow, RectParts parts) { roundRect(p, x, y, w, h, bg, ::corners[index], shadow, parts); } - void roundShadow(Painter &p, int32 x, int32 y, int32 w, int32 h, style::color shadow, RoundCorners index, RectParts parts) { + void roundShadow(Painter &p, int32_t x, int32_t y, int32_t w, int32_t h, style::color shadow, RoundCorners index, RectParts parts) { auto &corner = ::corners[index]; auto cornerWidth = corner.p[0].width() / cIntRetinaFactor(); auto cornerHeight = corner.p[0].height() / cIntRetinaFactor(); @@ -2759,8 +2751,8 @@ namespace { } } - void roundRect(Painter &p, int32 x, int32 y, int32 w, int32 h, style::color bg, ImageRoundRadius radius, RectParts parts) { - auto colorKey = ((uint32(bg->c.alpha()) & 0xFF) << 24) | ((uint32(bg->c.red()) & 0xFF) << 16) | ((uint32(bg->c.green()) & 0xFF) << 8) | ((uint32(bg->c.blue()) & 0xFF) << 24); + void roundRect(Painter &p, int32_t x, int32_t y, int32_t w, int32_t h, style::color bg, ImageRoundRadius radius, RectParts parts) { + auto colorKey = ((uint32_t(bg->c.alpha()) & 0xFF) << 24) | ((uint32_t(bg->c.red()) & 0xFF) << 16) | ((uint32_t(bg->c.green()) & 0xFF) << 8) | ((uint32_t(bg->c.blue()) & 0xFF) << 24); auto i = cornersMap.find(colorKey); if (i == cornersMap.cend()) { QImage images[4]; diff --git a/Telegram/SourceFiles/app.h b/Telegram/SourceFiles/app.h index 531abac00..aa38ae963 100644 --- a/Telegram/SourceFiles/app.h +++ b/Telegram/SourceFiles/app.h @@ -34,7 +34,7 @@ using PhotoItems = QHash; using DocumentItems = QHash; using WebPageItems = QHash; using GameItems = QHash; -using SharedContactItems = QHash; +using SharedContactItems = QHash; using GifItems = QHash; using PhotosData = QHash; @@ -53,8 +53,8 @@ namespace App { QString formatPhone(QString phone); TimeId onlineForSort(UserData *user, TimeId now); - int32 onlineWillChangeIn(UserData *user, TimeId now); - int32 onlineWillChangeIn(TimeId online, TimeId now); + int32_t onlineWillChangeIn(UserData *user, TimeId now); + int32_t onlineWillChangeIn(TimeId online, TimeId now); QString onlineText(UserData *user, TimeId now, bool precise = false); QString onlineText(TimeId online, TimeId now, bool precise = false); bool onlineColorUse(UserData *user, TimeId now); @@ -82,7 +82,7 @@ namespace App { void feedUserLink(MTPint userId, const MTPContactLink &myLink, const MTPContactLink &foreignLink); ImagePtr image(const MTPPhotoSize &size); - StorageImageLocation imageLocation(int32 w, int32 h, const MTPFileLocation &loc); + StorageImageLocation imageLocation(int32_t w, int32_t h, const MTPFileLocation &loc); StorageImageLocation imageLocation(const MTPPhotoSize &size); PhotoData *feedPhoto(const MTPPhoto &photo, const PreparedPhotoThumbs &thumbs); @@ -143,13 +143,13 @@ namespace App { PeerData *peerByName(const QString &username); QString peerName(const PeerData *peer, bool forDialogs = false); PhotoData *photo(const PhotoId &photo); - PhotoData *photoSet(const PhotoId &photo, PhotoData *convert, const uint64 &access, int32 date, const ImagePtr &thumb, const ImagePtr &medium, const ImagePtr &full); + PhotoData *photoSet(const PhotoId &photo, PhotoData *convert, const uint64_t &access, int32_t date, const ImagePtr &thumb, const ImagePtr &medium, const ImagePtr &full); DocumentData *document(const DocumentId &document); - DocumentData *documentSet(const DocumentId &document, DocumentData *convert, const uint64 &access, int32 version, int32 date, const QVector &attributes, const QString &mime, const ImagePtr &thumb, int32 dc, int32 size, const StorageImageLocation &thumbLocation); + DocumentData *documentSet(const DocumentId &document, DocumentData *convert, const uint64_t &access, int32_t version, int32_t date, const QVector &attributes, const QString &mime, const ImagePtr &thumb, int32_t dc, int32_t size, const StorageImageLocation &thumbLocation); WebPageData *webPage(const WebPageId &webPage); - WebPageData *webPageSet(const WebPageId &webPage, WebPageData *convert, const QString &type, const QString &url, const QString &displayUrl, const QString &siteName, const QString &title, const TextWithEntities &description, PhotoData *photo, DocumentData *doc, int32 duration, const QString &author, int32 pendingTill); + WebPageData *webPageSet(const WebPageId &webPage, WebPageData *convert, const QString &type, const QString &url, const QString &displayUrl, const QString &siteName, const QString &title, const TextWithEntities &description, PhotoData *photo, DocumentData *doc, int32_t duration, const QString &author, int32_t pendingTill); GameData *game(const GameId &game); - GameData *gameSet(const GameId &game, GameData *convert, const uint64 &accessHash, const QString &shortName, const QString &title, const QString &description, PhotoData *photo, DocumentData *doc); + GameData *gameSet(const GameId &game, GameData *convert, const uint64_t &accessHash, const QString &shortName, const QString &title, const QString &description, PhotoData *photo, DocumentData *doc); LocationData *location(const LocationCoords &coords); void forgetMedia(); @@ -157,7 +157,7 @@ namespace App { Histories &histories(); not_null history(const PeerId &peer); - History *historyFromDialog(const PeerId &peer, int32 unreadCnt, int32 maxInboxRead, int32 maxOutboxRead); + History *historyFromDialog(const PeerId &peer, int32_t unreadCnt, int32_t maxInboxRead, int32_t maxOutboxRead); History *historyLoaded(const PeerId &peer); HistoryItem *histItemById(ChannelId channelId, MsgId itemId); inline not_null history(const PeerData *peer) { @@ -182,12 +182,12 @@ namespace App { void historyRegDependency(HistoryItem *dependent, HistoryItem *dependency); void historyUnregDependency(HistoryItem *dependent, HistoryItem *dependency); - void historyRegRandom(uint64 randomId, const FullMsgId &itemId); - void historyUnregRandom(uint64 randomId); - FullMsgId histItemByRandom(uint64 randomId); - void historyRegSentData(uint64 randomId, const PeerId &peerId, const QString &text); - void historyUnregSentData(uint64 randomId); - void histSentDataByItem(uint64 randomId, PeerId &peerId, QString &text); + void historyRegRandom(uint64_t randomId, const FullMsgId &itemId); + void historyUnregRandom(uint64_t randomId); + FullMsgId histItemByRandom(uint64_t randomId); + void historyRegSentData(uint64_t randomId, const PeerId &peerId, const QString &text); + void historyUnregSentData(uint64_t randomId); + void histSentDataByItem(uint64_t randomId, PeerId &peerId, QString &text); void hoveredItem(HistoryItem *item); HistoryItem *hoveredItem(); @@ -206,7 +206,7 @@ namespace App { const style::font &monofont(); const QPixmap &emoji(); const QPixmap &emojiLarge(); - const QPixmap &emojiSingle(EmojiPtr emoji, int32 fontHeight); + const QPixmap &emojiSingle(EmojiPtr emoji, int32_t fontHeight); void clearHistories(); @@ -252,17 +252,17 @@ namespace App { void unregGameItem(GameData *data, HistoryItem *item); const GameItems &gameItems(); - void regSharedContactItem(int32 userId, HistoryItem *item); - void unregSharedContactItem(int32 userId, HistoryItem *item); + void regSharedContactItem(int32_t userId, HistoryItem *item); + void unregSharedContactItem(int32_t userId, HistoryItem *item); const SharedContactItems &sharedContactItems(); - QString phoneFromSharedContact(int32 userId); + QString phoneFromSharedContact(int32_t userId); void regGifItem(Media::Clip::Reader *reader, HistoryItem *item); void unregGifItem(Media::Clip::Reader *reader); void stopRoundVideoPlayback(); void stopGifItems(); - void regMuted(PeerData *peer, int32 changeIn); + void regMuted(PeerData *peer, int32_t changeIn); void unregMuted(PeerData *peer); void updateMuted(); @@ -276,23 +276,23 @@ namespace App { void complexLocationRect(Painter &p, QRect rect, ImageRoundRadius radius, ImageRoundCorners corners); QImage *cornersMask(ImageRoundRadius radius); - void roundRect(Painter &p, int32 x, int32 y, int32 w, int32 h, style::color bg, RoundCorners index, const style::color *shadow = nullptr, RectParts parts = RectPart::Full); + void roundRect(Painter &p, int32_t x, int32_t y, int32_t w, int32_t h, style::color bg, RoundCorners index, const style::color *shadow = nullptr, RectParts parts = RectPart::Full); inline void roundRect(Painter &p, const QRect &rect, style::color bg, RoundCorners index, const style::color *shadow = nullptr, RectParts parts = RectPart::Full) { return roundRect(p, rect.x(), rect.y(), rect.width(), rect.height(), bg, index, shadow, parts); } - void roundShadow(Painter &p, int32 x, int32 y, int32 w, int32 h, style::color shadow, RoundCorners index, RectParts parts = RectPart::Full); + void roundShadow(Painter &p, int32_t x, int32_t y, int32_t w, int32_t h, style::color shadow, RoundCorners index, RectParts parts = RectPart::Full); inline void roundShadow(Painter &p, const QRect &rect, style::color shadow, RoundCorners index, RectParts parts = RectPart::Full) { return roundShadow(p, rect.x(), rect.y(), rect.width(), rect.height(), shadow, index, parts); } - void roundRect(Painter &p, int32 x, int32 y, int32 w, int32 h, style::color bg, ImageRoundRadius radius, RectParts parts = RectPart::Full); + void roundRect(Painter &p, int32_t x, int32_t y, int32_t w, int32_t h, style::color bg, ImageRoundRadius radius, RectParts parts = RectPart::Full); inline void roundRect(Painter &p, const QRect &rect, style::color bg, ImageRoundRadius radius, RectParts parts = RectPart::Full) { return roundRect(p, rect.x(), rect.y(), rect.width(), rect.height(), bg, radius, parts); } struct WallPaper { - WallPaper(int32 id, ImagePtr thumb, ImagePtr full) : id(id), thumb(thumb), full(full) { + WallPaper(int32_t id, ImagePtr thumb, ImagePtr full) : id(id), thumb(thumb), full(full) { } - int32 id; + int32_t id; ImagePtr thumb; ImagePtr full; }; diff --git a/Telegram/SourceFiles/application.cpp b/Telegram/SourceFiles/application.cpp index 2e27d5063..1a0089819 100644 --- a/Telegram/SourceFiles/application.cpp +++ b/Telegram/SourceFiles/application.cpp @@ -24,13 +24,13 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "mainwidget.h" #include "mainwindow.h" #include "storage/localstorage.h" -#include "autoupdater.h" #include "window/notifications_manager.h" #include "messenger.h" #include "base/timer.h" namespace { +// @todo are there no other ways to get/set hex? QChar _toHex(ushort v) { v = v & 0x000F; return QChar::fromLatin1((v >= 10) ? ('a' + (v - 10)) : ('0' + v)); @@ -39,6 +39,7 @@ ushort _fromHex(QChar c) { return ((c.unicode() >= uchar('a')) ? (c.unicode() - uchar('a') + 10) : (c.unicode() - uchar('0'))) & 0x000F; } +// @todo urlencode/decode functions might help here?? QString _escapeTo7bit(const QString &str) { QString result; result.reserve(str.size() * 2); @@ -85,20 +86,13 @@ Application::Application(int &argc, char **argv) : QApplication(argc, argv) { connect(&_localSocket, SIGNAL(connected()), this, SLOT(socketConnected())); connect(&_localSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnected())); connect(&_localSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(socketError(QLocalSocket::LocalSocketError))); - connect(&_localSocket, SIGNAL(bytesWritten(qint64)), this, SLOT(socketWritten(qint64))); + connect(&_localSocket, SIGNAL(bytesWritten(int64_t)), this, SLOT(socketWritten(int64_t))); connect(&_localSocket, SIGNAL(readyRead()), this, SLOT(socketReading())); connect(&_localServer, SIGNAL(newConnection()), this, SLOT(newInstanceConnected())); QTimer::singleShot(0, this, SLOT(startApplication())); connect(this, SIGNAL(aboutToQuit()), this, SLOT(closeApplication())); -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - _updateCheckTimer.create(this); - connect(_updateCheckTimer, SIGNAL(timeout()), this, SLOT(updateCheck())); - connect(this, SIGNAL(updateFailed()), this, SLOT(onUpdateFailed())); - connect(this, SIGNAL(updateReady()), this, SLOT(onUpdateReady())); -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - if (cManyInstance()) { LOG(("Many instance allowed, starting...")); singleInstanceChecked(); @@ -135,7 +129,7 @@ void Application::socketConnected() { _localSocket.write(commands.toLatin1()); } -void Application::socketWritten(qint64/* bytes*/) { +void Application::socketWritten(int64_t/* bytes*/) { if (_localSocket.state() != QLocalSocket::ConnectedState) { LOG(("Socket is not connected %1").arg(_localSocket.state())); return; @@ -153,7 +147,7 @@ void Application::socketReading() { } _localSocketReadData.append(_localSocket.readAll()); if (QRegularExpression("RES:(\\d+);").match(_localSocketReadData).hasMatch()) { - uint64 pid = _localSocketReadData.mid(4, _localSocketReadData.length() - 5).toULongLong(); + uint64_t pid = _localSocketReadData.mid(4, _localSocketReadData.length() - 5).toULongLong(); psActivateProcess(pid); LOG(("Show command response received, pid = %1, activating and quitting...").arg(pid)); return App::quit(); @@ -185,14 +179,6 @@ void Application::socketError(QLocalSocket::LocalSocketError e) { } #endif // !Q_OS_WINRT -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - if (!cNoStartUpdate() && checkReadyUpdate()) { - cSetRestartingUpdate(true); - DEBUG_LOG(("Application Info: installing update instead of starting app...")); - return App::quit(); - } -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - singleInstanceChecked(); } @@ -249,8 +235,8 @@ void Application::readClients() { i->second.append(i->first->readAll()); if (i->second.size()) { QString cmds(QString::fromLatin1(i->second)); - int32 from = 0, l = cmds.length(); - for (int32 to = cmds.indexOf(QChar(';'), from); to >= from; to = (from < l) ? cmds.indexOf(QChar(';'), from) : -1) { + int32_t from = 0, l = cmds.length(); + for (int32_t to = cmds.indexOf(QChar(';'), from); to >= from; to = (from < l) ? cmds.indexOf(QChar(';'), from) : -1) { QStringRef cmd(&cmds, from, to - from); if (cmd.startsWith(qsl("CMD:"))) { Sandbox::execExternal(cmds.mid(from + 4, to - from - 4)); @@ -332,171 +318,8 @@ void Application::closeApplication() { _localClients.clear(); _localSocket.close(); - -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - delete _updateReply; - _updateReply = 0; - if (_updateChecker) _updateChecker->deleteLater(); - _updateChecker = 0; - if (_updateThread) { - _updateThread->quit(); - } - _updateThread = 0; -#endif // !TDESKTOP_DISABLE_AUTOUPDATE } -#ifndef TDESKTOP_DISABLE_AUTOUPDATE -void Application::updateCheck() { - startUpdateCheck(false); -} - -void Application::updateGotCurrent() { - if (!_updateReply || _updateThread) return; - - cSetLastUpdateCheck(unixtime()); - QRegularExpressionMatch m = QRegularExpression(qsl("^\\s*(\\d+)\\s*:\\s*([\\x21-\\x7f]+)\\s*$")).match(QString::fromLatin1(_updateReply->readAll())); - if (m.hasMatch()) { - uint64 currentVersion = m.captured(1).toULongLong(); - QString url = m.captured(2); - bool betaVersion = false; - if (url.startsWith(qstr("beta_"))) { - betaVersion = true; - url = url.mid(5) + '_' + countBetaVersionSignature(currentVersion); - } - if ((!betaVersion || cBetaVersion()) && currentVersion > (betaVersion ? cBetaVersion() : uint64(AppVersion))) { - _updateThread = new QThread(); - connect(_updateThread, SIGNAL(finished()), _updateThread, SLOT(deleteLater())); - _updateChecker = new UpdateChecker(_updateThread, url); - _updateThread->start(); - } - } - if (_updateReply) _updateReply->deleteLater(); - _updateReply = 0; - if (!_updateThread) { - QDir updates(cWorkingDir() + "tupdates"); - if (updates.exists()) { - QFileInfoList list = updates.entryInfoList(QDir::Files); - for (QFileInfoList::iterator i = list.begin(), e = list.end(); i != e; ++i) { - if (QRegularExpression("^(tupdate|tmacupd|tmac32upd|tlinuxupd|tlinux32upd)\\d+(_[a-z\\d]+)?$", QRegularExpression::CaseInsensitiveOption).match(i->fileName()).hasMatch()) { - QFile(i->absoluteFilePath()).remove(); - } - } - } - emit updateLatest(); - } - startUpdateCheck(true); - Local::writeSettings(); -} - -void Application::updateFailedCurrent(QNetworkReply::NetworkError e) { - LOG(("App Error: could not get current version (update check): %1").arg(e)); - if (_updateReply) _updateReply->deleteLater(); - _updateReply = 0; - - emit updateFailed(); - startUpdateCheck(true); -} - -void Application::onUpdateReady() { - if (_updateChecker) { - _updateChecker->deleteLater(); - _updateChecker = nullptr; - } - _updateCheckTimer->stop(); - - cSetLastUpdateCheck(unixtime()); - Local::writeSettings(); -} - -void Application::onUpdateFailed() { - if (_updateChecker) { - _updateChecker->deleteLater(); - _updateChecker = 0; - if (_updateThread) _updateThread->quit(); - _updateThread = 0; - } - - cSetLastUpdateCheck(unixtime()); - Local::writeSettings(); -} - -Application::UpdatingState Application::updatingState() { - if (!_updateThread) return Application::UpdatingNone; - if (!_updateChecker) return Application::UpdatingReady; - return Application::UpdatingDownload; -} - -int32 Application::updatingSize() { - if (!_updateChecker) return 0; - return _updateChecker->size(); -} - -int32 Application::updatingReady() { - if (!_updateChecker) return 0; - return _updateChecker->ready(); -} - -void Application::stopUpdate() { - if (_updateReply) { - _updateReply->abort(); - _updateReply->deleteLater(); - _updateReply = 0; - } - if (_updateChecker) { - _updateChecker->deleteLater(); - _updateChecker = 0; - if (_updateThread) _updateThread->quit(); - _updateThread = 0; - } -} - -void Application::startUpdateCheck(bool forceWait) { - if (!Sandbox::started()) return; - - _updateCheckTimer->stop(); - if (_updateThread || _updateReply || !cAutoUpdate() || cExeName().isEmpty()) return; - - int32 constDelay = cBetaVersion() ? 600 : UpdateDelayConstPart, randDelay = cBetaVersion() ? 300 : UpdateDelayRandPart; - int32 updateInSecs = cLastUpdateCheck() + constDelay + int32(rand() % randDelay) - unixtime(); - bool sendRequest = (updateInSecs <= 0 || updateInSecs > (constDelay + randDelay)); - if (!sendRequest && !forceWait) { - QDir updates(cWorkingDir() + "tupdates"); - if (updates.exists()) { - QFileInfoList list = updates.entryInfoList(QDir::Files); - for (QFileInfoList::iterator i = list.begin(), e = list.end(); i != e; ++i) { - if (QRegularExpression("^(tupdate|tmacupd|tmac32upd|tlinuxupd|tlinux32upd)\\d+(_[a-z\\d]+)?$", QRegularExpression::CaseInsensitiveOption).match(i->fileName()).hasMatch()) { - sendRequest = true; - } - } - } - } - if (cManyInstance() && !cDebug()) return; // only main instance is updating - - if (sendRequest) { - QUrl url(cUpdateURL()); - if (cBetaVersion()) { - url.setQuery(qsl("version=%1&beta=%2").arg(AppVersion).arg(cBetaVersion())); - } else if (cAlphaVersion()) { - url.setQuery(qsl("version=%1&alpha=1").arg(AppVersion)); - } else { - url.setQuery(qsl("version=%1").arg(AppVersion)); - } - QString u = url.toString(); - QNetworkRequest checkVersion(url); - if (_updateReply) _updateReply->deleteLater(); - - App::setProxySettings(_updateManager); - _updateReply = _updateManager.get(checkVersion); - connect(_updateReply, SIGNAL(finished()), this, SLOT(updateGotCurrent())); - connect(_updateReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(updateFailedCurrent(QNetworkReply::NetworkError))); - emit updateChecking(); - } else { - _updateCheckTimer->start((updateInSecs + 5) * 1000); - } -} - -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - inline Application *application() { return qobject_cast(QApplication::instance()); } @@ -548,73 +371,6 @@ void adjustSingleTimers() { base::Timer::Adjust(); } -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - -void startUpdateCheck() { - if (auto a = application()) { - return a->startUpdateCheck(false); - } -} - -void stopUpdate() { - if (auto a = application()) { - return a->stopUpdate(); - } -} - -Application::UpdatingState updatingState() { - if (auto a = application()) { - return a->updatingState(); - } - return Application::UpdatingNone; -} - -int32 updatingSize() { - if (auto a = application()) { - return a->updatingSize(); - } - return 0; -} - -int32 updatingReady() { - if (auto a = application()) { - return a->updatingReady(); - } - return 0; -} - -void updateChecking() { - if (auto a = application()) { - emit a->updateChecking(); - } -} - -void updateLatest() { - if (auto a = application()) { - emit a->updateLatest(); - } -} - -void updateProgress(qint64 ready, qint64 total) { - if (auto a = application()) { - emit a->updateProgress(ready, total); - } -} - -void updateFailed() { - if (auto a = application()) { - emit a->updateFailed(); - } -} - -void updateReady() { - if (auto a = application()) { - emit a->updateReady(); - } -} - -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - void connect(const char *signal, QObject *object, const char *method) { if (auto a = application()) { a->connect(a, signal, object, method); @@ -624,7 +380,7 @@ void connect(const char *signal, QObject *object, const char *method) { void launch() { Assert(application() != 0); - float64 dpi = Application::primaryScreen()->logicalDotsPerInch(); + double dpi = Application::primaryScreen()->logicalDotsPerInch(); if (dpi <= 108) { // 0-96-108 cSetScreenScale(dbisOne); } else if (dpi <= 132) { // 108-120-132 @@ -646,7 +402,7 @@ void launch() { } cSetRetina(true); cSetRetinaFactor(devicePixelRatio); - cSetIntRetinaFactor(int32(cRetinaFactor())); + cSetIntRetinaFactor(int32_t(cRetinaFactor())); cSetConfigScale(dbisOne); cSetRealScale(dbisOne); } diff --git a/Telegram/SourceFiles/application.h b/Telegram/SourceFiles/application.h index eec0ffc84..f0583882c 100644 --- a/Telegram/SourceFiles/application.h +++ b/Telegram/SourceFiles/application.h @@ -20,7 +20,9 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ #pragma once -class UpdateChecker; +#include "stdafx.h" +#include + class Application : public QApplication { Q_OBJECT @@ -41,7 +43,7 @@ public slots: void socketConnected(); void socketError(QLocalSocket::LocalSocketError e); void socketDisconnected(); - void socketWritten(qint64 bytes); + void socketWritten(int64_t bytes); void socketReading(); void newInstanceConnected(); @@ -64,47 +66,6 @@ private: bool _secondInstance = false; void singleInstanceChecked(); - -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - -// Autoupdating -public: - void startUpdateCheck(bool forceWait); - void stopUpdate(); - - enum UpdatingState { - UpdatingNone, - UpdatingDownload, - UpdatingReady, - }; - UpdatingState updatingState(); - int32 updatingSize(); - int32 updatingReady(); - -signals: - void updateChecking(); - void updateLatest(); - void updateProgress(qint64 ready, qint64 total); - void updateReady(); - void updateFailed(); - -public slots: - void updateCheck(); - - void updateGotCurrent(); - void updateFailedCurrent(QNetworkReply::NetworkError e); - - void onUpdateReady(); - void onUpdateFailed(); - -private: - object_ptr _updateCheckTimer = { nullptr }; - QNetworkReply *_updateReply = nullptr; - QNetworkAccessManager _updateManager; - QThread *_updateThread = nullptr; - UpdateChecker *_updateChecker = nullptr; - -#endif // !TDESKTOP_DISABLE_AUTOUPDATE }; namespace Sandbox { @@ -118,23 +79,6 @@ void execExternal(const QString &cmd); void adjustSingleTimers(); -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - -void startUpdateCheck(); -void stopUpdate(); - -Application::UpdatingState updatingState(); -int32 updatingSize(); -int32 updatingReady(); - -void updateChecking(); -void updateLatest(); -void updateProgress(qint64 ready, qint64 total); -void updateFailed(); -void updateReady(); - -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - void connect(const char *signal, QObject *object, const char *method); void launch(); diff --git a/Telegram/SourceFiles/auth_session.cpp b/Telegram/SourceFiles/auth_session.cpp index 08db86bfd..8c59de7d2 100644 --- a/Telegram/SourceFiles/auth_session.cpp +++ b/Telegram/SourceFiles/auth_session.cpp @@ -45,30 +45,30 @@ AuthSessionData::Variables::Variables() } QByteArray AuthSessionData::serialize() const { - auto size = sizeof(qint32) * 8; + auto size = sizeof(int32_t) * 8; for (auto i = _variables.soundOverrides.cbegin(), e = _variables.soundOverrides.cend(); i != e; ++i) { size += Serialize::stringSize(i.key()) + Serialize::stringSize(i.value()); } - size += _variables.groupStickersSectionHidden.size() * sizeof(quint64); + size += _variables.groupStickersSectionHidden.size() * sizeof(uint64_t); auto result = QByteArray(); result.reserve(size); { QDataStream stream(&result, QIODevice::WriteOnly); stream.setVersion(QDataStream::Qt_5_1); - stream << static_cast(_variables.selectorTab); - stream << qint32(_variables.lastSeenWarningSeen ? 1 : 0); - stream << qint32(_variables.tabbedSelectorSectionEnabled ? 1 : 0); - stream << qint32(_variables.soundOverrides.size()); + stream << static_cast(_variables.selectorTab); + stream << int32_t(_variables.lastSeenWarningSeen ? 1 : 0); + stream << int32_t(_variables.tabbedSelectorSectionEnabled ? 1 : 0); + stream << int32_t(_variables.soundOverrides.size()); for (auto i = _variables.soundOverrides.cbegin(), e = _variables.soundOverrides.cend(); i != e; ++i) { stream << i.key() << i.value(); } - stream << qint32(_variables.tabbedSelectorSectionTooltipShown); - stream << qint32(_variables.floatPlayerColumn); - stream << qint32(_variables.floatPlayerCorner); - stream << qint32(_variables.groupStickersSectionHidden.size()); + stream << int32_t(_variables.tabbedSelectorSectionTooltipShown); + stream << int32_t(_variables.floatPlayerColumn); + stream << int32_t(_variables.floatPlayerCorner); + stream << int32_t(_variables.groupStickersSectionHidden.size()); for (auto peerId : _variables.groupStickersSectionHidden) { - stream << quint64(peerId); + stream << uint64_t(peerId); } } return result; @@ -81,12 +81,12 @@ void AuthSessionData::constructFromSerialized(const QByteArray &serialized) { QDataStream stream(serialized); stream.setVersion(QDataStream::Qt_5_1); - qint32 selectorTab = static_cast(ChatHelpers::SelectorTab::Emoji); - qint32 lastSeenWarningSeen = 0; - qint32 tabbedSelectorSectionEnabled = 1; - qint32 tabbedSelectorSectionTooltipShown = 0; - qint32 floatPlayerColumn = static_cast(Window::Column::Second); - qint32 floatPlayerCorner = static_cast(RectPart::TopRight); + int32_t selectorTab = static_cast(ChatHelpers::SelectorTab::Emoji); + int32_t lastSeenWarningSeen = 0; + int32_t tabbedSelectorSectionEnabled = 1; + int32_t tabbedSelectorSectionTooltipShown = 0; + int32_t floatPlayerColumn = static_cast(Window::Column::Second); + int32_t floatPlayerCorner = static_cast(RectPart::TopRight); QMap soundOverrides; OrderedSet groupStickersSectionHidden; stream >> selectorTab; @@ -95,7 +95,7 @@ void AuthSessionData::constructFromSerialized(const QByteArray &serialized) { stream >> tabbedSelectorSectionEnabled; } if (!stream.atEnd()) { - auto count = qint32(0); + auto count = int32_t(0); stream >> count; if (stream.status() == QDataStream::Ok) { for (auto i = 0; i != count; ++i) { @@ -112,11 +112,11 @@ void AuthSessionData::constructFromSerialized(const QByteArray &serialized) { stream >> floatPlayerColumn >> floatPlayerCorner; } if (!stream.atEnd()) { - auto count = qint32(0); + auto count = int32_t(0); stream >> count; if (stream.status() == QDataStream::Ok) { for (auto i = 0; i != count; ++i) { - quint64 peerId; + uint64_t peerId; stream >> peerId; groupStickersSectionHidden.insert(peerId); } diff --git a/Telegram/SourceFiles/autoupdater.cpp b/Telegram/SourceFiles/autoupdater.cpp deleted file mode 100644 index a6aa4c296..000000000 --- a/Telegram/SourceFiles/autoupdater.cpp +++ /dev/null @@ -1,627 +0,0 @@ -/* -This file is part of Telegram Desktop, -the official desktop version of Telegram messaging app, see https://telegram.org - -Telegram Desktop is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -It is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -In addition, as a special exception, the copyright holders give permission -to link the code of portions of this program with the OpenSSL library. - -Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE -Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org -*/ - -#include "autoupdater.h" - -#include -#include -#include -#include - -#ifdef Q_OS_WIN // use Lzma SDK for win -#include -#else // Q_OS_WIN -#include -#endif // else of Q_OS_WIN - -#include "application.h" -#include "platform/platform_specific.h" - -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - -#ifdef Q_OS_WIN -typedef DWORD VerInt; -typedef WCHAR VerChar; -#else // Q_OS_WIN -typedef int VerInt; -typedef wchar_t VerChar; -#endif // Q_OS_WIN - -UpdateChecker::UpdateChecker(QThread *thread, const QString &url) : reply(0), already(0), full(0) { - updateUrl = url; - moveToThread(thread); - manager.moveToThread(thread); - App::setProxySettings(manager); - - connect(thread, SIGNAL(started()), this, SLOT(start())); - initOutput(); -} - -void UpdateChecker::initOutput() { - QString fileName; - QRegularExpressionMatch m = QRegularExpression(qsl("/([^/\\?]+)(\\?|$)")).match(updateUrl); - if (m.hasMatch()) { - fileName = m.captured(1).replace(QRegularExpression(qsl("[^a-zA-Z0-9_\\-]")), QString()); - } - if (fileName.isEmpty()) { - fileName = qsl("tupdate-%1").arg(rand_value() % 1000000); - } - QString dirStr = cWorkingDir() + qsl("tupdates/"); - fileName = dirStr + fileName; - QFileInfo file(fileName); - - QDir dir(dirStr); - if (dir.exists()) { - QFileInfoList all = dir.entryInfoList(QDir::Files); - for (QFileInfoList::iterator i = all.begin(), e = all.end(); i != e; ++i) { - if (i->absoluteFilePath() != file.absoluteFilePath()) { - QFile::remove(i->absoluteFilePath()); - } - } - } else { - dir.mkdir(dir.absolutePath()); - } - outputFile.setFileName(fileName); - if (file.exists()) { - uint64 fullSize = file.size(); - if (fullSize < INT_MAX) { - int32 goodSize = (int32)fullSize; - if (goodSize % UpdateChunk) { - goodSize = goodSize - (goodSize % UpdateChunk); - if (goodSize) { - if (outputFile.open(QIODevice::ReadOnly)) { - QByteArray goodData = outputFile.readAll().mid(0, goodSize); - outputFile.close(); - if (outputFile.open(QIODevice::WriteOnly)) { - outputFile.write(goodData); - outputFile.close(); - - QMutexLocker lock(&mutex); - already = goodSize; - } - } - } - } else { - QMutexLocker lock(&mutex); - already = goodSize; - } - } - if (!already) { - QFile::remove(fileName); - } - } -} - -void UpdateChecker::start() { - sendRequest(); -} - -void UpdateChecker::sendRequest() { - QNetworkRequest req(updateUrl); - QByteArray rangeHeaderValue = "bytes=" + QByteArray::number(already) + "-"; - req.setRawHeader("Range", rangeHeaderValue); - req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); - if (reply) reply->deleteLater(); - reply = manager.get(req); - connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(partFinished(qint64,qint64))); - connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(partFailed(QNetworkReply::NetworkError))); - connect(reply, SIGNAL(metaDataChanged()), this, SLOT(partMetaGot())); -} - -void UpdateChecker::partMetaGot() { - typedef QList Pairs; - Pairs pairs = reply->rawHeaderPairs(); - for (Pairs::iterator i = pairs.begin(), e = pairs.end(); i != e; ++i) { - if (QString::fromUtf8(i->first).toLower() == "content-range") { - QRegularExpressionMatch m = QRegularExpression(qsl("/(\\d+)([^\\d]|$)")).match(QString::fromUtf8(i->second)); - if (m.hasMatch()) { - { - QMutexLocker lock(&mutex); - full = m.captured(1).toInt(); - } - - Sandbox::updateProgress(already, full); - } - } - } -} - -int32 UpdateChecker::ready() { - QMutexLocker lock(&mutex); - return already; -} - -int32 UpdateChecker::size() { - QMutexLocker lock(&mutex); - return full; -} - -void UpdateChecker::partFinished(qint64 got, qint64 total) { - if (!reply) return; - - QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); - if (statusCode.isValid()) { - int status = statusCode.toInt(); - if (status != 200 && status != 206 && status != 416) { - LOG(("Update Error: Bad HTTP status received in partFinished(): %1").arg(status)); - return fatalFail(); - } - } - - if (!already && !full) { - QMutexLocker lock(&mutex); - full = total; - } - DEBUG_LOG(("Update Info: part %1 of %2").arg(got).arg(total)); - - if (!outputFile.isOpen()) { - if (!outputFile.open(QIODevice::Append)) { - LOG(("Update Error: Could not open output file '%1' for appending").arg(outputFile.fileName())); - return fatalFail(); - } - } - QByteArray r = reply->readAll(); - if (!r.isEmpty()) { - outputFile.write(r); - - QMutexLocker lock(&mutex); - already += r.size(); - } - if (got >= total) { - reply->deleteLater(); - reply = 0; - outputFile.close(); - unpackUpdate(); - } else { - Sandbox::updateProgress(already, full); - } -} - -void UpdateChecker::partFailed(QNetworkReply::NetworkError e) { - if (!reply) return; - - QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); - reply->deleteLater(); - reply = 0; - if (statusCode.isValid()) { - int status = statusCode.toInt(); - if (status == 416) { // Requested range not satisfiable - outputFile.close(); - unpackUpdate(); - return; - } - } - LOG(("Update Error: failed to download part starting from %1, error %2").arg(already).arg(e)); - Sandbox::updateFailed(); -} - -void UpdateChecker::fatalFail() { - clearAll(); - Sandbox::updateFailed(); -} - -void UpdateChecker::clearAll() { - psDeleteDir(cWorkingDir() + qsl("tupdates")); -} - -//QString winapiErrorWrap() { -// WCHAR errMsg[2048]; -// DWORD errorCode = GetLastError(); -// LPTSTR errorText = NULL, errorTextDefault = L"(Unknown error)"; -// FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorText, 0, 0); -// if (!errorText) { -// errorText = errorTextDefault; -// } -// StringCbPrintf(errMsg, sizeof(errMsg), L"Error code: %d, error message: %s", errorCode, errorText); -// if (errorText != errorTextDefault) { -// LocalFree(errorText); -// } -// return QString::fromWCharArray(errMsg); -//} - -void UpdateChecker::unpackUpdate() { - QByteArray packed; - if (!outputFile.open(QIODevice::ReadOnly)) { - LOG(("Update Error: cant read updates file!")); - return fatalFail(); - } - -#ifdef Q_OS_WIN // use Lzma SDK for win - const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header -#else // Q_OS_WIN - const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header -#endif // Q_OS_WIN - - QByteArray compressed = outputFile.readAll(); - int32 compressedLen = compressed.size() - hSize; - if (compressedLen <= 0) { - LOG(("Update Error: bad compressed size: %1").arg(compressed.size())); - return fatalFail(); - } - outputFile.close(); - - QString tempDirPath = cWorkingDir() + qsl("tupdates/temp"), readyFilePath = cWorkingDir() + qsl("tupdates/temp/ready"); - psDeleteDir(tempDirPath); - - QDir tempDir(tempDirPath); - if (tempDir.exists() || QFile(readyFilePath).exists()) { - LOG(("Update Error: cant clear tupdates/temp dir!")); - return fatalFail(); - } - - uchar sha1Buffer[20]; - bool goodSha1 = !memcmp(compressed.constData() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, compressedLen + hPropsLen + hOriginalSizeLen, sha1Buffer), hShaLen); - if (!goodSha1) { - LOG(("Update Error: bad SHA1 hash of update file!")); - return fatalFail(); - } - - RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast(AppAlphaVersion ? UpdatesPublicAlphaKey : UpdatesPublicKey), -1), 0, 0, 0); - if (!pbKey) { - LOG(("Update Error: cant read public rsa key!")); - return fatalFail(); - } - if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature - RSA_free(pbKey); - if (cAlphaVersion() || cBetaVersion()) { // try other public key, if we are in alpha or beta version - pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast(AppAlphaVersion ? UpdatesPublicKey : UpdatesPublicAlphaKey), -1), 0, 0, 0); - if (!pbKey) { - LOG(("Update Error: cant read public rsa key!")); - return fatalFail(); - } - if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature - RSA_free(pbKey); - LOG(("Update Error: bad RSA signature of update file!")); - return fatalFail(); - } - } else { - LOG(("Update Error: bad RSA signature of update file!")); - return fatalFail(); - } - } - RSA_free(pbKey); - - QByteArray uncompressed; - - int32 uncompressedLen; - memcpy(&uncompressedLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen); - uncompressed.resize(uncompressedLen); - - size_t resultLen = uncompressed.size(); -#ifdef Q_OS_WIN // use Lzma SDK for win - SizeT srcLen = compressedLen; - int uncompressRes = LzmaUncompress((uchar*)uncompressed.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE); - if (uncompressRes != SZ_OK) { - LOG(("Update Error: could not uncompress lzma, code: %1").arg(uncompressRes)); - return fatalFail(); - } -#else // Q_OS_WIN - lzma_stream stream = LZMA_STREAM_INIT; - - lzma_ret ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED); - if (ret != LZMA_OK) { - const char *msg; - switch (ret) { - case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; - case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break; - case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break; - default: msg = "Unknown error, possibly a bug"; break; - } - LOG(("Error initializing the decoder: %1 (error code %2)").arg(msg).arg(ret)); - return fatalFail(); - } - - stream.avail_in = compressedLen; - stream.next_in = (uint8_t*)(compressed.constData() + hSize); - stream.avail_out = resultLen; - stream.next_out = (uint8_t*)uncompressed.data(); - - lzma_ret res = lzma_code(&stream, LZMA_FINISH); - if (stream.avail_in) { - LOG(("Error in decompression, %1 bytes left in _in of %2 whole.").arg(stream.avail_in).arg(compressedLen)); - return fatalFail(); - } else if (stream.avail_out) { - LOG(("Error in decompression, %1 bytes free left in _out of %2 whole.").arg(stream.avail_out).arg(resultLen)); - return fatalFail(); - } - lzma_end(&stream); - if (res != LZMA_OK && res != LZMA_STREAM_END) { - const char *msg; - switch (res) { - case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; - case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break; - case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break; - case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break; - case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break; - default: msg = "Unknown error, possibly a bug"; break; - } - LOG(("Error in decompression: %1 (error code %2)").arg(msg).arg(res)); - return fatalFail(); - } -#endif // Q_OS_WIN - - tempDir.mkdir(tempDir.absolutePath()); - - quint32 version; - { - QDataStream stream(uncompressed); - stream.setVersion(QDataStream::Qt_5_1); - - stream >> version; - if (stream.status() != QDataStream::Ok) { - LOG(("Update Error: cant read version from downloaded stream, status: %1").arg(stream.status())); - return fatalFail(); - } - - quint64 betaVersion = 0; - if (version == 0x7FFFFFFF) { // beta version - stream >> betaVersion; - if (stream.status() != QDataStream::Ok) { - LOG(("Update Error: cant read beta version from downloaded stream, status: %1").arg(stream.status())); - return fatalFail(); - } - if (!cBetaVersion() || betaVersion <= cBetaVersion()) { - LOG(("Update Error: downloaded beta version %1 is not greater, than mine %2").arg(betaVersion).arg(cBetaVersion())); - return fatalFail(); - } - } else if (int32(version) <= AppVersion) { - LOG(("Update Error: downloaded version %1 is not greater, than mine %2").arg(version).arg(AppVersion)); - return fatalFail(); - } - - quint32 filesCount; - stream >> filesCount; - if (stream.status() != QDataStream::Ok) { - LOG(("Update Error: cant read files count from downloaded stream, status: %1").arg(stream.status())); - return fatalFail(); - } - if (!filesCount) { - LOG(("Update Error: update is empty!")); - return fatalFail(); - } - for (uint32 i = 0; i < filesCount; ++i) { - QString relativeName; - quint32 fileSize; - QByteArray fileInnerData; - bool executable = false; - - stream >> relativeName >> fileSize >> fileInnerData; -#if defined Q_OS_MAC || defined Q_OS_LINUX - stream >> executable; -#endif // Q_OS_MAC || Q_OS_LINUX - if (stream.status() != QDataStream::Ok) { - LOG(("Update Error: cant read file from downloaded stream, status: %1").arg(stream.status())); - return fatalFail(); - } - if (fileSize != quint32(fileInnerData.size())) { - LOG(("Update Error: bad file size %1 not matching data size %2").arg(fileSize).arg(fileInnerData.size())); - return fatalFail(); - } - - QFile f(tempDirPath + '/' + relativeName); - if (!QDir().mkpath(QFileInfo(f).absolutePath())) { - LOG(("Update Error: cant mkpath for file '%1'").arg(tempDirPath + '/' + relativeName)); - return fatalFail(); - } - if (!f.open(QIODevice::WriteOnly)) { - LOG(("Update Error: cant open file '%1' for writing").arg(tempDirPath + '/' + relativeName)); - return fatalFail(); - } - auto writtenBytes = f.write(fileInnerData); - if (writtenBytes != fileSize) { - f.close(); - LOG(("Update Error: cant write file '%1', desiredSize: %2, write result: %3").arg(tempDirPath + '/' + relativeName).arg(fileSize).arg(writtenBytes)); - return fatalFail(); - } - f.close(); - if (executable) { - QFileDevice::Permissions p = f.permissions(); - p |= QFileDevice::ExeOwner | QFileDevice::ExeUser | QFileDevice::ExeGroup | QFileDevice::ExeOther; - f.setPermissions(p); - } - } - - // create tdata/version file - tempDir.mkdir(QDir(tempDirPath + qsl("/tdata")).absolutePath()); - std::wstring versionString = ((version % 1000) ? QString("%1.%2.%3").arg(int(version / 1000000)).arg(int((version % 1000000) / 1000)).arg(int(version % 1000)) : QString("%1.%2").arg(int(version / 1000000)).arg(int((version % 1000000) / 1000))).toStdWString(); - - VerInt versionNum = VerInt(version), versionLen = VerInt(versionString.size() * sizeof(VerChar)); - VerChar versionStr[32]; - memcpy(versionStr, versionString.c_str(), versionLen); - - QFile fVersion(tempDirPath + qsl("/tdata/version")); - if (!fVersion.open(QIODevice::WriteOnly)) { - LOG(("Update Error: cant write version file '%1'").arg(tempDirPath + qsl("/version"))); - return fatalFail(); - } - fVersion.write((const char*)&versionNum, sizeof(VerInt)); - if (versionNum == 0x7FFFFFFF) { // beta version - fVersion.write((const char*)&betaVersion, sizeof(quint64)); - } else { - fVersion.write((const char*)&versionLen, sizeof(VerInt)); - fVersion.write((const char*)&versionStr[0], versionLen); - } - fVersion.close(); - } - - QFile readyFile(readyFilePath); - if (readyFile.open(QIODevice::WriteOnly)) { - if (readyFile.write("1", 1)) { - readyFile.close(); - } else { - LOG(("Update Error: cant write ready file '%1'").arg(readyFilePath)); - return fatalFail(); - } - } else { - LOG(("Update Error: cant create ready file '%1'").arg(readyFilePath)); - return fatalFail(); - } - outputFile.remove(); - - Sandbox::updateReady(); -} - -UpdateChecker::~UpdateChecker() { - delete reply; - reply = 0; -} - -bool checkReadyUpdate() { - QString readyFilePath = cWorkingDir() + qsl("tupdates/temp/ready"), readyPath = cWorkingDir() + qsl("tupdates/temp"); - if (!QFile(readyFilePath).exists() || cExeName().isEmpty()) { - if (QDir(cWorkingDir() + qsl("tupdates/ready")).exists() || QDir(cWorkingDir() + qsl("tupdates/temp")).exists()) { - UpdateChecker::clearAll(); - } - return false; - } - - // check ready version - QString versionPath = readyPath + qsl("/tdata/version"); - { - QFile fVersion(versionPath); - if (!fVersion.open(QIODevice::ReadOnly)) { - LOG(("Update Error: cant read version file '%1'").arg(versionPath)); - UpdateChecker::clearAll(); - return false; - } - VerInt versionNum; - if (fVersion.read((char*)&versionNum, sizeof(VerInt)) != sizeof(VerInt)) { - LOG(("Update Error: cant read version from file '%1'").arg(versionPath)); - UpdateChecker::clearAll(); - return false; - } - if (versionNum == 0x7FFFFFFF) { // beta version - quint64 betaVersion = 0; - if (fVersion.read((char*)&betaVersion, sizeof(quint64)) != sizeof(quint64)) { - LOG(("Update Error: cant read beta version from file '%1'").arg(versionPath)); - UpdateChecker::clearAll(); - return false; - } - if (!cBetaVersion() || betaVersion <= cBetaVersion()) { - LOG(("Update Error: cant install beta version %1 having beta version %2").arg(betaVersion).arg(cBetaVersion())); - UpdateChecker::clearAll(); - return false; - } - } else if (versionNum <= AppVersion) { - LOG(("Update Error: cant install version %1 having version %2").arg(versionNum).arg(AppVersion)); - UpdateChecker::clearAll(); - return false; - } - fVersion.close(); - } - -#ifdef Q_OS_WIN - QString curUpdater = (cExeDir() + qsl("Updater.exe")); - QFileInfo updater(cWorkingDir() + qsl("tupdates/temp/Updater.exe")); -#elif defined Q_OS_MAC // Q_OS_WIN - QString curUpdater = (cExeDir() + cExeName() + qsl("/Contents/Frameworks/Updater")); - QFileInfo updater(cWorkingDir() + qsl("tupdates/temp/Telegram.app/Contents/Frameworks/Updater")); -#elif defined Q_OS_LINUX // Q_OS_MAC - QString curUpdater = (cExeDir() + qsl("Updater")); - QFileInfo updater(cWorkingDir() + qsl("tupdates/temp/Updater")); -#endif // Q_OS_LINUX - if (!updater.exists()) { - QFileInfo current(curUpdater); - if (!current.exists()) { - UpdateChecker::clearAll(); - return false; - } - if (!QFile(current.absoluteFilePath()).copy(updater.absoluteFilePath())) { - UpdateChecker::clearAll(); - return false; - } - } -#ifdef Q_OS_WIN - if (CopyFile(updater.absoluteFilePath().toStdWString().c_str(), curUpdater.toStdWString().c_str(), FALSE) == FALSE) { - DWORD errorCode = GetLastError(); - if (errorCode == ERROR_ACCESS_DENIED) { // we are in write-protected dir, like Program Files - cSetWriteProtected(true); - return true; - } else { - UpdateChecker::clearAll(); - return false; - } - } - if (DeleteFile(updater.absoluteFilePath().toStdWString().c_str()) == FALSE) { - UpdateChecker::clearAll(); - return false; - } -#elif defined Q_OS_MAC // Q_OS_WIN - QDir().mkpath(QFileInfo(curUpdater).absolutePath()); - DEBUG_LOG(("Update Info: moving %1 to %2...").arg(updater.absoluteFilePath()).arg(curUpdater)); - if (!objc_moveFile(updater.absoluteFilePath(), curUpdater)) { - UpdateChecker::clearAll(); - return false; - } -#elif defined Q_OS_LINUX // Q_OS_MAC - if (!linuxMoveFile(QFile::encodeName(updater.absoluteFilePath()).constData(), QFile::encodeName(curUpdater).constData())) { - UpdateChecker::clearAll(); - return false; - } -#endif // Q_OS_LINUX - return true; -} - -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - -QString countBetaVersionSignature(uint64 version) { // duplicated in packer.cpp - if (cBetaPrivateKey().isEmpty()) { - LOG(("Error: Trying to count beta version signature without beta private key!")); - return QString(); - } - - QByteArray signedData = (qstr("TelegramBeta_") + QString::number(version, 16).toLower()).toUtf8(); - - static const int32 shaSize = 20, keySize = 128; - - uchar sha1Buffer[shaSize]; - hashSha1(signedData.constData(), signedData.size(), sha1Buffer); // count sha1 - - uint32 siglen = 0; - - RSA *prKey = PEM_read_bio_RSAPrivateKey(BIO_new_mem_buf(const_cast(cBetaPrivateKey().constData()), -1), 0, 0, 0); - if (!prKey) { - LOG(("Error: Could not read beta private key!")); - return QString(); - } - if (RSA_size(prKey) != keySize) { - LOG(("Error: Bad beta private key size: %1").arg(RSA_size(prKey))); - RSA_free(prKey); - return QString(); - } - QByteArray signature; - signature.resize(keySize); - if (RSA_sign(NID_sha1, (const uchar*)(sha1Buffer), shaSize, (uchar*)(signature.data()), &siglen, prKey) != 1) { // count signature - LOG(("Error: Counting beta version signature failed!")); - RSA_free(prKey); - return QString(); - } - RSA_free(prKey); - - if (siglen != keySize) { - LOG(("Error: Bad beta version signature length: %1").arg(siglen)); - return QString(); - } - - signature = signature.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); - signature = signature.replace('-', '8').replace('_', 'B'); - return QString::fromUtf8(signature.mid(19, 32)); -} diff --git a/Telegram/SourceFiles/autoupdater.h b/Telegram/SourceFiles/autoupdater.h deleted file mode 100644 index 58100857c..000000000 --- a/Telegram/SourceFiles/autoupdater.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -This file is part of Telegram Desktop, -the official desktop version of Telegram messaging app, see https://telegram.org - -Telegram Desktop is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -It is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -In addition, as a special exception, the copyright holders give permission -to link the code of portions of this program with the OpenSSL library. - -Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE -Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org -*/ -#pragma once - -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - -#include -#include -#include - -class UpdateChecker : public QObject { - Q_OBJECT - -public: - UpdateChecker(QThread *thread, const QString &url); - - void unpackUpdate(); - - int32 ready(); - int32 size(); - - static void clearAll(); - - ~UpdateChecker(); - -public slots: - - void start(); - void partMetaGot(); - void partFinished(qint64 got, qint64 total); - void partFailed(QNetworkReply::NetworkError e); - void sendRequest(); - -private: - void initOutput(); - - void fatalFail(); - - QString updateUrl; - QNetworkAccessManager manager; - QNetworkReply *reply; - int32 already, full; - QFile outputFile; - - QMutex mutex; - -}; - -bool checkReadyUpdate(); - -#else // TDESKTOP_DISABLE_AUTOUPDATE -class UpdateChecker : public QObject { - Q_OBJECT -}; - -#endif // TDESKTOP_DISABLE_AUTOUPDATE - -QString countBetaVersionSignature(uint64 version); diff --git a/Telegram/SourceFiles/base/algorithm.h b/Telegram/SourceFiles/base/algorithm.h index 44188b05e..e3aafda87 100644 --- a/Telegram/SourceFiles/base/algorithm.h +++ b/Telegram/SourceFiles/base/algorithm.h @@ -22,6 +22,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org namespace base { +// @todo use ranges-v3 here template decltype(auto) for_each(Range &&range, Method &&method) { return std::for_each( diff --git a/Telegram/SourceFiles/base/observer.h b/Telegram/SourceFiles/base/observer.h index 362c6d42b..6b1797da4 100644 --- a/Telegram/SourceFiles/base/observer.h +++ b/Telegram/SourceFiles/base/observer.h @@ -22,6 +22,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include #include +#include #include "base/type_traits.h" namespace base { diff --git a/Telegram/SourceFiles/base/runtime_composer.cpp b/Telegram/SourceFiles/base/runtime_composer.cpp index c88a1b0ac..f61df7a31 100644 --- a/Telegram/SourceFiles/base/runtime_composer.cpp +++ b/Telegram/SourceFiles/base/runtime_composer.cpp @@ -21,7 +21,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "base/runtime_composer.h" struct RuntimeComposerMetadatasMap { - QMap data; + QMap data; ~RuntimeComposerMetadatasMap() { for_const (const RuntimeComposerMetadata *p, data) { delete p; @@ -29,7 +29,7 @@ struct RuntimeComposerMetadatasMap { } }; -const RuntimeComposerMetadata *GetRuntimeComposerMetadata(uint64 mask) { +const RuntimeComposerMetadata *GetRuntimeComposerMetadata(uint64_t mask) { static RuntimeComposerMetadatasMap RuntimeComposerMetadatas; static QMutex RuntimeComposerMetadatasMutex; diff --git a/Telegram/SourceFiles/base/runtime_composer.h b/Telegram/SourceFiles/base/runtime_composer.h index 276f26c76..88d4bb607 100644 --- a/Telegram/SourceFiles/base/runtime_composer.h +++ b/Telegram/SourceFiles/base/runtime_composer.h @@ -84,7 +84,7 @@ struct RuntimeComponent { } return MyIndex.loadAcquire() - 1; } - static uint64 Bit() { + static uint64_t Bit() { return (1ULL << Index()); } @@ -103,7 +103,7 @@ protected: class RuntimeComposerMetadata { public: - RuntimeComposerMetadata(uint64 mask) : _mask(mask) { + RuntimeComposerMetadata(uint64_t mask) : _mask(mask) { for (int i = 0; i != 64; ++i) { auto componentBit = (1ULL << i); if (_mask & componentBit) { @@ -130,26 +130,26 @@ public: std::size_t offsets[64] = { 0 }; int last = 64; - bool equals(uint64 mask) const { + bool equals(uint64_t mask) const { return _mask == mask; } - uint64 maskadd(uint64 mask) const { + uint64_t maskadd(uint64_t mask) const { return _mask | mask; } - uint64 maskremove(uint64 mask) const { + uint64_t maskremove(uint64_t mask) const { return _mask & (~mask); } private: - uint64 _mask; + uint64_t _mask; }; -const RuntimeComposerMetadata *GetRuntimeComposerMetadata(uint64 mask); +const RuntimeComposerMetadata *GetRuntimeComposerMetadata(uint64_t mask); class RuntimeComposer { public: - RuntimeComposer(uint64 mask = 0) : _data(zerodata()) { + RuntimeComposer(uint64_t mask = 0) : _data(zerodata()) { if (mask) { auto meta = GetRuntimeComposerMetadata(mask); @@ -212,7 +212,7 @@ public: } protected: - void UpdateComponents(uint64 mask = 0) { + void UpdateComponents(uint64_t mask = 0) { if (!_meta()->equals(mask)) { RuntimeComposer tmp(mask); tmp.swap(*this); @@ -228,10 +228,10 @@ protected: } } } - void AddComponents(uint64 mask = 0) { + void AddComponents(uint64_t mask = 0) { UpdateComponents(_meta()->maskadd(mask)); } - void RemoveComponents(uint64 mask = 0) { + void RemoveComponents(uint64_t mask = 0) { UpdateComponents(_meta()->maskremove(mask)); } diff --git a/Telegram/SourceFiles/base/flags_tests.cpp b/Telegram/SourceFiles/base/tests/flags_tests.cpp similarity index 100% rename from Telegram/SourceFiles/base/flags_tests.cpp rename to Telegram/SourceFiles/base/tests/flags_tests.cpp diff --git a/Telegram/SourceFiles/base/flat_map_tests.cpp b/Telegram/SourceFiles/base/tests/flat_map_tests.cpp similarity index 100% rename from Telegram/SourceFiles/base/flat_map_tests.cpp rename to Telegram/SourceFiles/base/tests/flat_map_tests.cpp diff --git a/Telegram/SourceFiles/base/flat_set_tests.cpp b/Telegram/SourceFiles/base/tests/flat_set_tests.cpp similarity index 100% rename from Telegram/SourceFiles/base/flat_set_tests.cpp rename to Telegram/SourceFiles/base/tests/flat_set_tests.cpp diff --git a/Telegram/SourceFiles/base/tests_main.cpp b/Telegram/SourceFiles/base/tests/tests_main.cpp similarity index 100% rename from Telegram/SourceFiles/base/tests_main.cpp rename to Telegram/SourceFiles/base/tests/tests_main.cpp diff --git a/Telegram/SourceFiles/base/virtual_method.h b/Telegram/SourceFiles/base/virtual_method.h deleted file mode 100644 index 4edebad4f..000000000 --- a/Telegram/SourceFiles/base/virtual_method.h +++ /dev/null @@ -1,717 +0,0 @@ -/* -This file is part of Telegram Desktop, -the official desktop version of Telegram messaging app, see https://telegram.org - -Telegram Desktop is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -It is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -In addition, as a special exception, the copyright holders give permission -to link the code of portions of this program with the OpenSSL library. - -Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE -Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org -*/ -#pragma once - -namespace base { - -template -class virtual_object; - -template -class virtual_method; - -template -class virtual_override; - -namespace virtual_methods { - -struct child_entry; -using is_parent_check = bool(*)(const child_entry &possible_parent); -struct child_entry { - is_parent_check check_is_parent; - int *table_index; -}; -using child_entries = std::vector; - -// Recursive method to find if some class is a child of some other class. -template -struct is_parent { - static inline bool check(const child_entry &possible_parent) { - // Generate a good error message if ConcreteObject is not a child of virtual_object<>. - using all_objects_must_derive_virtual_object = typename ConcreteObject::virtual_object_parent; - using ConcreteObjectParent = all_objects_must_derive_virtual_object; - return (possible_parent.check_is_parent == &is_parent::check) - || is_parent::check(possible_parent); - } -}; - -template <> -struct is_parent { - static inline bool check(const child_entry &possible_parent) { - return (possible_parent.check_is_parent == &is_parent::check); - } -}; - -// Just force the compiler not to optimize away the object that "enforce" points at. -inline void dont_optimize_away(void *enforce) { - static volatile void *result = nullptr; - if (result) { - result = enforce; - } -} - -template -struct dont_optimize_away_struct { -}; - -inline bool first_dispatch_fired(bool did_fire = false) { - static bool fired = false; - if (did_fire) { - fired = true; - } - return fired; -} - -template -class object_registrator { -public: - inline object_registrator() { - Assert(!first_dispatch_fired()); - Creator(child_entry { - &is_parent::check, - &_index, - }); - } - static inline int &Index() { - return _index; - } - -private: - static int _index; - -}; - -template -int object_registrator::_index = -1; - -class object_base { -protected: - virtual ~object_base() = default; - -}; - -template -struct multi_index_collector; -template -struct override_key_collector_helper; -template -struct table_fill_entry_helper; -template -struct table_count_size; - -} // namespace virtual_methods - -// This should be a base class for every child object in your hierarchy. -// It registers this child in the root virtual_objects classes list. -// Also it holds its own index in the classes list that is used for fast -// invoking of methods from the virtual tables in different virtual_methods. -template -class virtual_object : public ParentObject { -protected: - virtual ~virtual_object() { - virtual_methods::dont_optimize_away(&_virtual_object_registrator); - } - -private: - using virtual_object_parent = ParentObject; - - friend struct virtual_methods::is_parent; - template - friend struct virtual_methods::multi_index_collector; - template - friend struct virtual_methods::override_key_collector_helper; - template - friend class virtual_object; - template - friend class virtual_method; - - static inline void virtual_object_register_child(const virtual_methods::child_entry &entry) { - return ParentObject::virtual_object_register_child(entry); - } - - using virtual_object_registrator = virtual_methods::object_registrator; - static virtual_object_registrator _virtual_object_registrator; - using virtual_object_dont_optimize_away_registrator = virtual_methods::dont_optimize_away_struct; - - static inline int &virtual_object_child_index_static() { - return virtual_object_registrator::Index(); - } - int &virtual_object_child_index() override { - return virtual_object_child_index_static(); - } - -}; - -template -typename virtual_object::virtual_object_registrator virtual_object::_virtual_object_registrator = {}; - -// This should be a base class for the root of the whole hierarchy. -// It holds the table of all child classes in a list. -// This list is used by virtual_methods to generate virtual table. -template -class virtual_object : public virtual_methods::object_base { -protected: - virtual ~virtual_object() { - virtual_methods::dont_optimize_away(&_virtual_object_registrator); - } - -private: - using virtual_object_parent = void; - - friend struct virtual_methods::is_parent; - template - friend struct virtual_methods::table_count_size; - template - friend struct virtual_methods::multi_index_collector; - template - friend struct virtual_methods::override_key_collector_helper; - template - friend struct virtual_methods::table_fill_entry_helper; - template - friend class virtual_object; - template - friend class virtual_method; - - static inline virtual_methods::child_entries &virtual_object_get_child_entries() { - static virtual_methods::child_entries entries; - return entries; - } - - // Registers a new child class. - // After that on the next call to virtual_method::virtual_method_prepare_table() will - // generate a new virtual table for that virtual method. - static inline void virtual_object_register_child(const virtual_methods::child_entry &entry) { - auto &entries = virtual_object_get_child_entries(); - for (auto i = entries.begin(), e = entries.end(); i != e; ++i) { - if (entry.check_is_parent(*i)) { - *entry.table_index = (i - entries.begin()); - i = entries.insert(i, entry); - for (++i, e = entries.end(); i != e; ++i) { - ++*(i->table_index); - } - return; - } - } - *entry.table_index = entries.size(); - entries.push_back(entry); - } - - using virtual_object_registrator = virtual_methods::object_registrator; - static virtual_object_registrator _virtual_object_registrator; - using virtual_object_dont_optimize_away_registrator = virtual_methods::dont_optimize_away_struct; - - static inline int &virtual_object_child_index_static() { - return virtual_object_registrator::Index(); - } - virtual int &virtual_object_child_index() { - return virtual_object_child_index_static(); - } - -}; - -template -typename virtual_object::virtual_object_registrator virtual_object::_virtual_object_registrator = {}; - -namespace virtual_methods { - -template -struct is_virtual_argument : public std::integral_constant::is_pointer::value - ? std::is_base_of::pointed_type>::value - : false> { -}; - -template -class multi_int_wrap { -public: - inline multi_int_wrap(int *indices) : _indices(indices) { - } - inline multi_int_wrap subindex() const { - static_assert(N > 0, "Wrong multi_int_wrap created!"); - return multi_int_wrap(_indices + 1); - } - inline int ¤t() const { - return *_indices; - } - -private: - int *_indices; - -}; - -template -class multi_int_wrap<0, Instance> { -public: - inline multi_int_wrap(int *indices) { - } - inline int current() const { - return 1; - } - -}; - -template -using multi_index_wrap = multi_int_wrap; -template -using multi_size_wrap = multi_int_wrap; - -template -struct multi_index_collector { - static constexpr int N = sizeof...(ConcreteArgs) + 1; - static inline void call(multi_index_wrap indices, ConcreteArg arg, ConcreteArgs... args) { - indices.current() = computeIndex(is_virtual_argument(), arg); - multi_index_collector::call(indices.subindex(), args...); - } - - static inline int computeIndex(std::integral_constant, ConcreteArg arg) { - return 0; - } - static inline int computeIndex(std::integral_constant, ConcreteArg arg) { - return arg->virtual_object_child_index(); - } - -}; - -template <> -struct multi_index_collector<> { - static inline void call(multi_index_wrap<0> indices) { - } -}; - -template -class override_key; - -template -class multi_int { -public: - inline multi_int_wrap data_wrap() { - return multi_int_wrap(_indices); - } - - template - static inline multi_int collect(ConcreteArgs... args) { - multi_int result; - multi_index_collector::call(result.data_wrap(), args...); - return result; - } - - inline void reset() { - memset(_indices, 0, sizeof(_indices)); - } - - inline int value(int index) const { - return _indices[index]; - } - - inline void copy(multi_int_wrap other) { - memcpy(_indices, &other.current(), sizeof(_indices)); - } - -private: - int _indices[N] = { 0 }; - friend class override_key; - -}; - -template -using multi_index = multi_int; -template -using multi_size = multi_int; - -template -class table_data_wrap { -public: - inline table_data_wrap(Call *data, multi_size_wrap size) : _data(data), _size(size) { - } - inline table_data_wrap operator[](int index) const { - return table_data_wrap(_data + index * _size.subindex().current(), _size.subindex()); - } - inline Call &operator[](multi_index_wrap index) const { - return (*this)[index.current()][index.subindex()]; - } - inline int size() const { - return count_size(std::integral_constant()); - } - -private: - template - inline int count_size(std::integral_constant) const { - return _size.current() / _size.subindex().current(); - } - inline int count_size(std::integral_constant) const { - return _size.current(); - } - - Call *_data; - multi_size_wrap _size; - -}; - -template -class table_data_wrap { -public: - inline table_data_wrap(Call *data, multi_size_wrap<0> size) : _data(data) { - } - inline Call &operator[](multi_index_wrap<0> index) const { - return *_data; - } - -private: - Call *_data; - -}; - -template -class table_data_wrap; - -template -struct table_count_size { - static constexpr int N = sizeof...(Args) + 1; - static inline void call(multi_size_wrap index) { - auto subindex = index.subindex(); - table_count_size::call(subindex); - index.current() = count(is_virtual_argument()) * subindex.current(); - } - - static inline int count(std::integral_constant) { - return 1; - } - static inline int count(std::integral_constant) { - return base::type_traits::pointed_type::virtual_object_get_child_entries().size(); - } - -}; - -template <> -struct table_count_size<> { - static inline void call(multi_size_wrap<0> index) { - } -}; - -template -class table_data { -public: - inline table_data_wrap data_wrap() { - return table_data_wrap(_data.data(), _size.data_wrap()); - } - - inline Call &operator[](multi_index index) { - int flat_index = 0; - for (int i = 0; i != N - 1; ++i) { - flat_index += _size.value(i + 1) * index.value(i); - } - flat_index += index.value(N - 1); - return _data[flat_index]; - } - - template - inline bool changed() { - if (!_data.empty()) { - return false; - } - - multi_size size; - table_count_size::call(size.data_wrap()); - _size = size; - _data.resize(_size.value(0), nullptr); - return true; - } - -private: - std::vector _data; - multi_size _size; - -}; - -template -class table_data { -public: - inline table_data_wrap data_wrap() { - return table_data_wrap(&_call, multi_size_wrap<0>(nullptr)); - } - - inline Call &operator[](multi_index<0> index) { - return _call; - } - - inline bool changed() const { - return false; - } - -private: - Call _call = nullptr; - -}; - -template -struct table_fill_entry_helper; - -template -struct table_fill_entry_helper { - static constexpr int N = sizeof...(Args) + 1; - - static inline bool call(table_data_wrap table, multi_index_wrap index, Call &fill) { - auto start = index.current(); - for (auto i = start, count = table.size(); i != count; ++i) { - auto foundGoodType = good(is_virtual_argument(), start, index.current()); - if (foundGoodType) { - index.current() = i; - if (table_fill_entry_helper::call(table[i], index.subindex(), fill)) { - return true; - } - } - } - index.current() = start; - return false; - } - - static inline bool good(std::integral_constant, int start, int current) { - return (start == current); - } - static inline bool good(std::integral_constant, int start, int current) { - using BaseObject = typename base::type_traits::pointed_type; - auto &entries = BaseObject::virtual_object_get_child_entries(); - return (start == current) || entries[start].check_is_parent(entries[current]); - } - -}; - -template -struct table_fill_entry_helper { - static inline bool call(table_data_wrap table, multi_index_wrap<0> index, Call &fill) { - if (auto overrideMethod = table[index]) { - fill = overrideMethod; - return true; - } - return false; - } -}; - -template -struct table_fill_entry; - -template -struct table_fill_entry { - using Call = ReturnType(*)(BaseMethod*, Args...); - static inline void call(table_data_wrap table, multi_index_wrap index, Call &fill) { - table_fill_entry_helper::call(table, index, fill); - } -}; - -template -inline void fill_entry(table_data_wrap table, multi_index_wrap index, Call &fill) { - return virtual_methods::table_fill_entry::call(table, index, fill); -} - -template -struct override_key_collector_helper; - -template -struct override_key_collector_helper { - static inline void call(int **indices) { - setValue(is_virtual_argument(), indices); - override_key_collector_helper::call(indices); - } - - static inline void setValue(std::integral_constant, int **indices) { - indices[M] = nullptr; - } - static inline void setValue(std::integral_constant, int **indices) { - using ConcreteObject = typename base::type_traits::pointed_type; - using IsParentCheckStruct = is_parent; - using IsParentCheckPointer = decltype(&IsParentCheckStruct::check); - using override_key_collector_dont_optimize_away = dont_optimize_away_struct; - override_key_collector_dont_optimize_away dont_optimize_away_object; - (void)dont_optimize_away_object; - - // Check that is_parent<> can be instantiated. - // So every ConcreteObject is a valid child of virtual_object<>. - dont_optimize_away(reinterpret_cast(&IsParentCheckStruct::check)); - indices[M] = &ConcreteObject::virtual_object_child_index_static(); - } - -}; - -template -struct override_key_collector_helper { - static inline void call(int **indices) { - } -}; - -template -struct override_key_collector; - -template -struct override_key_collector { - static inline void call(int **indices) { - override_key_collector_helper<0, ConcreteArgs...>::call(indices); - } -}; - -template -class override_key { -public: - inline multi_index value() const { - multi_index result; - for (int i = 0; i != N; ++i) { - auto pointer = _indices[i]; - result._indices[i] = (pointer ? *pointer : 0); - } - return result; - } - - friend inline bool operator<(const override_key &k1, const override_key &k2) { - for (int i = 0; i != N; ++i) { - auto pointer1 = k1._indices[i], pointer2 = k2._indices[i]; - if (pointer1 < pointer2) { - return true; - } else if (pointer1 > pointer2) { - return false; - } - } - return false; - } - - template - inline void collect() { - override_key_collector::call(_indices); - } - -private: - int *_indices[N]; - -}; - -template -struct static_cast_helper; - -template -struct static_cast_helper { - static inline ReturnType call(BaseMethod *context, Args ...args) { - return ConcreteMethod::call(context, static_cast(args)...); - } -}; - -} // namespace virtual_methods - -// This is a base class for all your virtual methods. -// It dispatches a call to one of the registered virtual_overrides -// or calls the fallback method of the BaseMethod class. -template -class virtual_method { - static constexpr int N = sizeof...(Args); - using virtual_method_call = ReturnType(*)(BaseMethod *context, Args... args); - -public: - inline ReturnType call(Args... args) { - auto context = static_cast(this); - auto index = virtual_methods::multi_index::collect(args...); - auto &table = virtual_method_prepare_table(); - auto &entry = table[index]; - if (!entry) { - virtual_methods::fill_entry(table.data_wrap(), index.data_wrap(), entry); - if (!entry) { - entry = &virtual_method::virtual_method_base_instance; - } - } - return (*entry)(context, args...); - } - -private: - // This map of methods contains only the original registered overrides. - using virtual_method_override_key = virtual_methods::override_key; - using virtual_method_override_map = std::map; - static inline virtual_method_override_map &virtual_method_get_override_map() { - static virtual_method_override_map override_map; - return override_map; - } - - // This method generates and returns a virtual table which holds a method - // for any child in the hierarchy or nullptr if none of the virtual_overrides fit. - using virtual_method_table_data = virtual_methods::table_data; - static inline virtual_method_table_data &virtual_method_get_table_data() { - static virtual_method_table_data virtual_table; - return virtual_table; - } - - static inline virtual_method_table_data &virtual_method_prepare_table() { - auto &virtual_table = virtual_method_get_table_data(); - if (virtual_table.template changed()) { - virtual_methods::first_dispatch_fired(true); - - // The class hierarchy has changed - we need to generate the virtual table once again. - // All other handlers will be placed if they're called. - for (auto &i : virtual_method_get_override_map()) { - virtual_table[i.first.value()] = i.second; - } - } - return virtual_table; - } - - static ReturnType virtual_method_base_instance(BaseMethod *context, Args... args) { - return BaseMethod::default_call(context, args...); - } - - template - static ReturnType virtual_method_override_instance(BaseMethod *context, Args... args) { - return virtual_methods::static_cast_helper::call(context, args...); - } - - template - static inline void virtual_method_register_override() { - auto call = &virtual_method_override_instance; - - virtual_methods::override_key key; - key.template collect(); - - virtual_method_get_override_map()[key] = call; - } - - template - friend class virtual_override; - -}; - -template -class virtual_override { -protected: - virtual ~virtual_override() { - virtual_methods::dont_optimize_away(&_virtual_override_registrator); - } - -private: - class virtual_override_registrator { - public: - inline virtual_override_registrator() { - Assert(!virtual_methods::first_dispatch_fired()); - BaseMethod::template virtual_method_register_override(); - } - - }; - static virtual_override_registrator _virtual_override_registrator; - using virtual_override_dont_optimize_away_registrator = virtual_methods::dont_optimize_away_struct; - -}; - -template -typename virtual_override::virtual_override_registrator virtual_override::_virtual_override_registrator = {}; - -} // namespace base diff --git a/Telegram/SourceFiles/base/weak_unique_ptr.h b/Telegram/SourceFiles/base/weak_unique_ptr.h index dd74f6d43..7ae74f12f 100644 --- a/Telegram/SourceFiles/base/weak_unique_ptr.h +++ b/Telegram/SourceFiles/base/weak_unique_ptr.h @@ -20,6 +20,8 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ #pragma once +// @todo replace this with std::experimental::observer_ptr + namespace base { class enable_weak_from_this; diff --git a/Telegram/SourceFiles/base/zlib_help.h b/Telegram/SourceFiles/base/zlib_help.h index 1aad0ea46..27f7e5f7a 100644 --- a/Telegram/SourceFiles/base/zlib_help.h +++ b/Telegram/SourceFiles/base/zlib_help.h @@ -23,8 +23,8 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ #pragma once -#include "zip.h" -#include "unzip.h" +#include "minizip/zip.h" +#include "minizip/unzip.h" namespace zlib { namespace internal { @@ -243,7 +243,7 @@ public: } auto size = fileInfo.uncompressed_size; - if (size > static_cast(fileSizeLimit)) { + if (size > static_cast(fileSizeLimit)) { if (_error == UNZ_OK) _error = -1; LOG(("Error: current file is too large (should be less than %1, got %2) in a zip file.").arg(fileSizeLimit).arg(size)); return QByteArray(); diff --git a/Telegram/SourceFiles/boxes/CMakeLists.txt b/Telegram/SourceFiles/boxes/CMakeLists.txt new file mode 100644 index 000000000..ce9eb74b2 --- /dev/null +++ b/Telegram/SourceFiles/boxes/CMakeLists.txt @@ -0,0 +1,36 @@ +# Unused: cotire PCH needs more rigid structure. +# To do: get rid of the PCH requirement for more flexible build structure. +add_library(tg_boxes STATIC + about_box.cpp + abstract_box.cpp + add_contact_box.cpp + autolock_box.cpp + background_box.cpp + calendar_box.cpp + change_phone_box.cpp + confirm_box.cpp + confirm_phone_box.cpp + connection_box.cpp + download_path_box.cpp + edit_color_box.cpp + edit_participant_box.cpp + edit_privacy_box.cpp + language_box.cpp + local_storage_box.cpp + mute_settings_box.cpp + notifications_box.cpp + passcode_box.cpp + peer_list_box.cpp + peer_list_controllers.cpp + photo_crop_box.cpp + rate_call_box.cpp + report_box.cpp + self_destruction_box.cpp + send_files_box.cpp + sessions_box.cpp + share_box.cpp + sticker_set_box.cpp + stickers_box.cpp + username_box.cpp +) +add_dependencies(tg_boxes boxes_styles_output) diff --git a/Telegram/SourceFiles/boxes/about_box.cpp b/Telegram/SourceFiles/boxes/about_box.cpp index 6f2ed8504..f545e9ec9 100644 --- a/Telegram/SourceFiles/boxes/about_box.cpp +++ b/Telegram/SourceFiles/boxes/about_box.cpp @@ -23,7 +23,6 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "lang/lang_keys.h" #include "mainwidget.h" #include "mainwindow.h" -#include "autoupdater.h" #include "boxes/confirm_box.h" #include "application.h" #include "ui/widgets/buttons.h" @@ -61,23 +60,7 @@ void AboutBox::resizeEvent(QResizeEvent *e) { } void AboutBox::showVersionHistory() { - if (cRealBetaVersion()) { - auto url = qsl("https://tdesktop.com/"); - switch (cPlatform()) { - case dbipWindows: url += qsl("win/%1.zip"); break; - case dbipMac: url += qsl("mac/%1.zip"); break; - case dbipMacOld: url += qsl("mac32/%1.zip"); break; - case dbipLinux32: url += qsl("linux32/%1.tar.xz"); break; - case dbipLinux64: url += qsl("linux/%1.tar.xz"); break; - } - url = url.arg(qsl("tbeta%1_%2").arg(cRealBetaVersion()).arg(countBetaVersionSignature(cRealBetaVersion()))); - - Application::clipboard()->setText(url); - - Ui::show(Box("The link to the current private beta version of Telegram Desktop was copied to the clipboard.")); - } else { - QDesktopServices::openUrl(qsl("https://desktop.telegram.org/changelog")); - } + QDesktopServices::openUrl(qsl("https://desktop.telegram.org/changelog")); } void AboutBox::keyPressEvent(QKeyEvent *e) { diff --git a/Telegram/SourceFiles/boxes/abstract_box.cpp b/Telegram/SourceFiles/boxes/abstract_box.cpp index 91dd88f7c..59e7f78e3 100644 --- a/Telegram/SourceFiles/boxes/abstract_box.cpp +++ b/Telegram/SourceFiles/boxes/abstract_box.cpp @@ -104,7 +104,7 @@ void BoxContent::onDraggingScrollDelta(int delta) { } void BoxContent::onDraggingScrollTimer() { - auto delta = (_draggingScrollDelta > 0) ? qMin(_draggingScrollDelta * 3 / 20 + 1, int32(MaxScrollSpeed)) : qMax(_draggingScrollDelta * 3 / 20 - 1, -int32(MaxScrollSpeed)); + auto delta = (_draggingScrollDelta > 0) ? qMin(_draggingScrollDelta * 3 / 20 + 1, int32_t(MaxScrollSpeed)) : qMax(_draggingScrollDelta * 3 / 20 - 1, -int32_t(MaxScrollSpeed)); _scroll->scrollToY(_scroll->scrollTop() + delta); } diff --git a/Telegram/SourceFiles/boxes/add_contact_box.cpp b/Telegram/SourceFiles/boxes/add_contact_box.cpp index 04d1a890e..29100231b 100644 --- a/Telegram/SourceFiles/boxes/add_contact_box.cpp +++ b/Telegram/SourceFiles/boxes/add_contact_box.cpp @@ -221,11 +221,11 @@ void AddContactBox::onSave() { } _sentName = firstName; if (_user) { - _contactId = rand_value(); + _contactId = rand_value(); QVector v(1, MTP_inputPhoneContact(MTP_long(_contactId), MTP_string(_user->phone()), MTP_string(firstName), MTP_string(lastName))); _addRequest = MTP::send(MTPcontacts_ImportContacts(MTP_vector(v)), rpcDone(&AddContactBox::onSaveUserDone), rpcFail(&AddContactBox::onSaveUserFail)); } else { - _contactId = rand_value(); + _contactId = rand_value(); QVector v(1, MTP_inputPhoneContact(MTP_long(_contactId), MTP_string(phone), MTP_string(firstName), MTP_string(lastName))); _addRequest = MTP::send(MTPcontacts_ImportContacts(MTP_vector(v)), rpcDone(&AddContactBox::onImportDone)); } @@ -745,8 +745,8 @@ void SetupChannelBox::onChange() { } _checkTimer.stop(); } else { - int32 len = name.size(); - for (int32 i = 0; i < len; ++i) { + int32_t len = name.size(); + for (int32_t i = 0; i < len; ++i) { QChar ch = name.at(i); if ((ch < 'A' || ch > 'Z') && (ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') && ch != '_') { if (_errorText != lang(lng_create_channel_link_bad_symbols)) { @@ -1498,8 +1498,8 @@ void RevokePublicLinkBox::Inner::paintChat(Painter &p, const ChatRow &row, bool p.setPen(st::contactsNameFg); - int32 namex = st::contactsPadding.left() + st::contactsPhotoSize + st::contactsPadding.left(); - int32 namew = width() - namex - st::contactsPadding.right() - (_revokeWidth + st::contactsCheckPosition.x() * 2); + int32_t namex = st::contactsPadding.left() + st::contactsPhotoSize + st::contactsPadding.left(); + int32_t namew = width() - namex - st::contactsPadding.right() - (_revokeWidth + st::contactsCheckPosition.x() * 2); if (peer->isVerified()) { auto icon = &st::dialogsVerifiedIcon; namew -= icon->width(); diff --git a/Telegram/SourceFiles/boxes/add_contact_box.h b/Telegram/SourceFiles/boxes/add_contact_box.h index c49e8f14f..5dcb3f34d 100644 --- a/Telegram/SourceFiles/boxes/add_contact_box.h +++ b/Telegram/SourceFiles/boxes/add_contact_box.h @@ -84,7 +84,7 @@ private: bool _retrying = false; bool _invertOrder = false; - uint64 _contactId = 0; + uint64_t _contactId = 0; mtpRequestId _addRequest = 0; QString _sentName; @@ -185,7 +185,7 @@ private: std::shared_ptr> _privacyGroup; object_ptr> _public; object_ptr> _private; - int32 _aboutPublicWidth, _aboutPublicHeight; + int32_t _aboutPublicWidth, _aboutPublicHeight; Text _aboutPublic, _aboutPrivate; object_ptr _link; diff --git a/Telegram/SourceFiles/boxes/background_box.cpp b/Telegram/SourceFiles/boxes/background_box.cpp index 6366da106..34569c90f 100644 --- a/Telegram/SourceFiles/boxes/background_box.cpp +++ b/Telegram/SourceFiles/boxes/background_box.cpp @@ -115,10 +115,10 @@ void BackgroundBox::Inner::gotWallpapers(const MTPVector &result) auto &d = w.c_wallPaper(); auto &sizes = d.vsizes.v; const MTPPhotoSize *thumb = 0, *full = 0; - int32 thumbLevel = -1, fullLevel = -1; + int32_t thumbLevel = -1, fullLevel = -1; for (QVector::const_iterator j = sizes.cbegin(), e = sizes.cend(); j != e; ++j) { char size = 0; - int32 w = 0, h = 0; + int32_t w = 0, h = 0; switch (j->type()) { case mtpc_photoSize: { auto &s = j->c_photoSize().vtype.v; @@ -136,7 +136,7 @@ void BackgroundBox::Inner::gotWallpapers(const MTPVector &result) } if (!size || !w || !h) continue; - int32 newThumbLevel = qAbs((st::backgroundSize.width() * cIntRetinaFactor()) - w), newFullLevel = qAbs(2560 - w); + int32_t newThumbLevel = qAbs((st::backgroundSize.width() * cIntRetinaFactor()) - w), newFullLevel = qAbs(2560 - w); if (thumbLevel < 0 || newThumbLevel < thumbLevel) { thumbLevel = newThumbLevel; thumb = &(*j); diff --git a/Telegram/SourceFiles/boxes/confirm_box.h b/Telegram/SourceFiles/boxes/confirm_box.h index 9ea2e457a..e9ed81acf 100644 --- a/Telegram/SourceFiles/boxes/confirm_box.h +++ b/Telegram/SourceFiles/boxes/confirm_box.h @@ -115,7 +115,7 @@ private: not_null _channel; Text _text; - int32 _textWidth, _textHeight; + int32_t _textWidth, _textHeight; QRect _invitationLink; bool _linkOver = false; @@ -141,7 +141,7 @@ private: ChatData *_chat; Text _text, _note; - int32 _textWidth, _textHeight; + int32_t _textWidth, _textHeight; }; diff --git a/Telegram/SourceFiles/boxes/connection_box.cpp b/Telegram/SourceFiles/boxes/connection_box.cpp index cf75dae50..f211e92aa 100644 --- a/Telegram/SourceFiles/boxes/connection_box.cpp +++ b/Telegram/SourceFiles/boxes/connection_box.cpp @@ -303,7 +303,7 @@ void AutoDownloadBox::resizeEvent(QResizeEvent *e) { void AutoDownloadBox::onSave() { bool changed = false; - int32 autoDownloadPhoto = (_photoPrivate->checked() ? 0 : dbiadNoPrivate) | (_photoGroups->checked() ? 0 : dbiadNoGroups); + int32_t autoDownloadPhoto = (_photoPrivate->checked() ? 0 : dbiadNoPrivate) | (_photoGroups->checked() ? 0 : dbiadNoGroups); if (cAutoDownloadPhoto() != autoDownloadPhoto) { bool enabledPrivate = ((cAutoDownloadPhoto() & dbiadNoPrivate) && !(autoDownloadPhoto & dbiadNoPrivate)); bool enabledGroups = ((cAutoDownloadPhoto() & dbiadNoGroups) && !(autoDownloadPhoto & dbiadNoGroups)); @@ -316,7 +316,7 @@ void AutoDownloadBox::onSave() { } changed = true; } - int32 autoDownloadAudio = (_audioPrivate->checked() ? 0 : dbiadNoPrivate) | (_audioGroups->checked() ? 0 : dbiadNoGroups); + int32_t autoDownloadAudio = (_audioPrivate->checked() ? 0 : dbiadNoPrivate) | (_audioGroups->checked() ? 0 : dbiadNoGroups); if (cAutoDownloadAudio() != autoDownloadAudio) { bool enabledPrivate = ((cAutoDownloadAudio() & dbiadNoPrivate) && !(autoDownloadAudio & dbiadNoPrivate)); bool enabledGroups = ((cAutoDownloadAudio() & dbiadNoGroups) && !(autoDownloadAudio & dbiadNoGroups)); @@ -330,7 +330,7 @@ void AutoDownloadBox::onSave() { } changed = true; } - int32 autoDownloadGif = (_gifPrivate->checked() ? 0 : dbiadNoPrivate) | (_gifGroups->checked() ? 0 : dbiadNoGroups); + int32_t autoDownloadGif = (_gifPrivate->checked() ? 0 : dbiadNoPrivate) | (_gifGroups->checked() ? 0 : dbiadNoGroups); if (cAutoDownloadGif() != autoDownloadGif) { bool enabledPrivate = ((cAutoDownloadGif() & dbiadNoPrivate) && !(autoDownloadGif & dbiadNoPrivate)); bool enabledGroups = ((cAutoDownloadGif() & dbiadNoGroups) && !(autoDownloadGif & dbiadNoGroups)); diff --git a/Telegram/SourceFiles/boxes/edit_color_box.cpp b/Telegram/SourceFiles/boxes/edit_color_box.cpp index 897da15fb..2a483d0d8 100644 --- a/Telegram/SourceFiles/boxes/edit_color_box.cpp +++ b/Telegram/SourceFiles/boxes/edit_color_box.cpp @@ -30,10 +30,10 @@ class EditColorBox::Picker : public TWidget { public: Picker(QWidget *parent, QColor color); - float64 valueX() const { + double valueX() const { return _x; } - float64 valueY() const { + double valueY() const { return _y; } @@ -64,8 +64,8 @@ private: QImage _palette; bool _paletteInvalidated = false; - float64 _x = 0.; - float64 _y = 0.; + double _x = 0.; + double _y = 0.; bool _choosing = false; base::Observable _changed; @@ -150,8 +150,8 @@ void EditColorBox::Picker::preparePalette() { _paletteInvalidated = false; auto size = _palette.width(); - auto ints = reinterpret_cast(_palette.bits()); - auto intsAddPerLine = (_palette.bytesPerLine() - size * sizeof(uint32)) / sizeof(uint32); + auto ints = reinterpret_cast(_palette.bits()); + auto intsAddPerLine = (_palette.bytesPerLine() - size * sizeof(uint32_t)) / sizeof(uint32_t); constexpr auto Large = 1024 * 1024; constexpr auto LargeBit = 20; // n / Large == (n >> LargeBit) @@ -190,8 +190,8 @@ void EditColorBox::Picker::preparePalette() { } void EditColorBox::Picker::updateCurrentPoint(QPoint localPosition) { - auto x = snap(localPosition.x(), 0, width()) / float64(width()); - auto y = snap(localPosition.y(), 0, height()) / float64(height()); + auto x = snap(localPosition.x(), 0, width()) / double(width()); + auto y = snap(localPosition.y(), 0, height()) / double(height()); if (_x != x || _y != y) { _x = x; _y = y; @@ -236,10 +236,10 @@ public: base::Observable &changed() { return _changed; } - float64 value() const { + double value() const { return _value; } - void setValue(float64 value) { + void setValue(double value) { _value = snap(value, 0., 1.); update(); } @@ -256,8 +256,8 @@ protected: void mouseReleaseEvent(QMouseEvent *e) override; private: - float64 valueFromColor(QColor color) const; - float64 valueFromHue(int hue) const; + double valueFromColor(QColor color) const; + double valueFromHue(int hue) const; bool isHorizontal() const { return (_direction == Direction::Horizontal); } @@ -271,7 +271,7 @@ private: Type _type = Type::Hue; QColor _color; - float64 _value = 0; + double _value = 0; QImage _mask; QPixmap _pixmap; @@ -339,8 +339,8 @@ void EditColorBox::Slider::generatePixmap() { auto size = (isHorizontal() ? width() : height()) * cIntRetinaFactor(); auto image = QImage(size, cIntRetinaFactor(), QImage::Format_ARGB32_Premultiplied); image.setDevicePixelRatio(cRetinaFactor()); - auto ints = reinterpret_cast(image.bits()); - auto intsPerLine = image.bytesPerLine() / sizeof(uint32); + auto ints = reinterpret_cast(image.bits()); + auto intsPerLine = image.bytesPerLine() / sizeof(uint32_t); auto intsPerLineAdded = intsPerLine - size; constexpr auto Large = 1024 * 1024; @@ -408,11 +408,11 @@ void EditColorBox::Slider::colorUpdated() { update(); } -float64 EditColorBox::Slider::valueFromColor(QColor color) const { +double EditColorBox::Slider::valueFromColor(QColor color) const { return (_type == Type::Hue) ? valueFromHue(color.hsvHue()) : color.alphaF(); } -float64 EditColorBox::Slider::valueFromHue(int hue) const { +double EditColorBox::Slider::valueFromHue(int hue) const { return (1. - snap(hue, 0, 360) / 360.); } @@ -430,7 +430,7 @@ void EditColorBox::Slider::updatePixmapFromMask() { void EditColorBox::Slider::updateCurrentPoint(QPoint localPosition) { auto coord = (isHorizontal() ? localPosition.x() : localPosition.y()) - st::colorSliderSkip; auto maximum = (isHorizontal() ? width() : height()) - 2 * st::colorSliderSkip; - auto value = snap(coord, 0, maximum) / float64(maximum); + auto value = snap(coord, 0, maximum) / double(maximum); if (_value != value) { _value = value; update(); @@ -909,4 +909,4 @@ void EditColorBox::setRGB(int red, int green, int blue, int alpha) { updateControlsFromColor(); updateHSVFields(); update(); -} \ No newline at end of file +} diff --git a/Telegram/SourceFiles/boxes/passcode_box.cpp b/Telegram/SourceFiles/boxes/passcode_box.cpp index 6df3d36e8..76bec0541 100644 --- a/Telegram/SourceFiles/boxes/passcode_box.cpp +++ b/Telegram/SourceFiles/boxes/passcode_box.cpp @@ -141,8 +141,8 @@ void PasscodeBox::paintEvent(QPaintEvent *e) { Painter p(this); - int32 w = st::boxWidth - st::boxPadding.left() * 1.5; - int32 abouty = (_passwordHint->isHidden() ? ((_reenterPasscode->isHidden() ? (_oldPasscode->y() + (_hasRecovery && !_hintText.isEmpty() ? st::passcodeTextLine : 0)) : _reenterPasscode->y()) + st::passcodeSkip) : _passwordHint->y()) + _oldPasscode->height() + st::passcodeLittleSkip + st::passcodeAboutSkip; + int32_t w = st::boxWidth - st::boxPadding.left() * 1.5; + int32_t abouty = (_passwordHint->isHidden() ? ((_reenterPasscode->isHidden() ? (_oldPasscode->y() + (_hasRecovery && !_hintText.isEmpty() ? st::passcodeTextLine : 0)) : _reenterPasscode->y()) + st::passcodeSkip) : _passwordHint->y()) + _oldPasscode->height() + st::passcodeLittleSkip + st::passcodeAboutSkip; p.setPen(st::boxTextFg); _about.drawLeft(p, st::boxPadding.left(), abouty, w, width()); @@ -170,7 +170,7 @@ void PasscodeBox::resizeEvent(QResizeEvent *e) { BoxContent::resizeEvent(e); bool has = _cloudPwd ? (!_curSalt.isEmpty()) : Global::LocalPasscode(); - int32 w = st::boxWidth - st::boxPadding.left() - st::boxPadding.right(); + int32_t w = st::boxWidth - st::boxPadding.left() - st::boxPadding.right(); _oldPasscode->resize(w, _oldPasscode->height()); _oldPasscode->moveToLeft(st::boxPadding.left(), st::passcodePadding.top()); _newPasscode->resize(w, _newPasscode->height()); @@ -443,7 +443,7 @@ void RecoverBox::paintEvent(QPaintEvent *e) { p.setFont(st::normalFont); p.setPen(st::boxTextFg); - int32 w = st::boxWidth - st::boxPadding.left() * 1.5; + int32_t w = st::boxWidth - st::boxPadding.left() * 1.5; p.drawText(QRect(st::boxPadding.left(), _recoverCode->y() - st::passcodeTextLine - st::passcodePadding.top(), w, st::passcodePadding.top() + st::passcodeTextLine), _pattern, style::al_left); if (!_error.isEmpty()) { diff --git a/Telegram/SourceFiles/boxes/peer_list_box.cpp b/Telegram/SourceFiles/boxes/peer_list_box.cpp index 11127b473..8f1f8d0fd 100644 --- a/Telegram/SourceFiles/boxes/peer_list_box.cpp +++ b/Telegram/SourceFiles/boxes/peer_list_box.cpp @@ -34,9 +34,12 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "storage/file_download.h" #include "window/themes/window_theme.h" -PeerListBox::PeerListBox(QWidget*, std::unique_ptr controller, base::lambda)> init) -: _controller(std::move(controller)) -, _init(std::move(init)) { +PeerListBox::PeerListBox(QWidget* + , std::unique_ptr controller + , base::lambda)> init) + : _controller(std::move(controller)) + , _init(std::move(init)) +{ Expects(_controller != nullptr); } @@ -49,7 +52,7 @@ void PeerListBox::createMultiSelect() { _select.create(this, std::move(entity), margins, std::move(callback)); _select->entity()->setSubmittedCallback([this](bool chtrlShiftEnter) { _inner->submitted(); }); _select->entity()->setQueryChangedCallback([this](const QString &query) { searchQueryChanged(query); }); - _select->entity()->setItemRemovedCallback([this](uint64 itemId) { + _select->entity()->setItemRemovedCallback([this](uint64_t itemId) { if (auto peer = App::peerLoaded(itemId)) { if (auto row = peerListFindRow(peer->id)) { _inner->changeCheckState(row, false, PeerListRow::SetStyle::Animated); @@ -341,7 +344,7 @@ int PeerListBox::peerListSelectedRowsCount() { std::vector> PeerListBox::peerListCollectSelectedRows() { auto result = std::vector> {}; - auto items = _select ? _select->entity()->getItems() : QVector {}; + auto items = _select ? _select->entity()->getItems() : QVector {}; if (!items.empty()) { result.reserve(items.size()); for_const (auto itemId, items) { @@ -496,7 +499,7 @@ void PeerListRow::setStatusText(const QString &text) { _status.setText(st::defaultTextStyle, text, _textNameOptions); } -float64 PeerListRow::checkedRatio() { +double PeerListRow::checkedRatio() { return _checkbox ? _checkbox->checkedAnimationRatio() : 0.; } diff --git a/Telegram/SourceFiles/boxes/peer_list_box.h b/Telegram/SourceFiles/boxes/peer_list_box.h index 394ba0088..7f1749fbc 100644 --- a/Telegram/SourceFiles/boxes/peer_list_box.h +++ b/Telegram/SourceFiles/boxes/peer_list_box.h @@ -43,7 +43,7 @@ inline auto PaintUserpicCallback(PeerData *peer) { }; } -using PeerListRowId = uint64; +using PeerListRowId = uint64_t; class PeerListRow { public: PeerListRow(not_null peer); @@ -139,7 +139,7 @@ public: void stopLastRipple(); void paintRipple(Painter &p, TimeMs ms, int x, int y, int outerWidth); void paintUserpic(Painter &p, TimeMs ms, int x, int y, int outerWidth); - float64 checkedRatio(); + double checkedRatio(); void setNameFirstChars(const OrderedSet &nameFirstChars) { _nameFirstChars = nameFirstChars; diff --git a/Telegram/SourceFiles/boxes/peer_list_controllers.cpp b/Telegram/SourceFiles/boxes/peer_list_controllers.cpp index 49c11281f..7fe337d22 100644 --- a/Telegram/SourceFiles/boxes/peer_list_controllers.cpp +++ b/Telegram/SourceFiles/boxes/peer_list_controllers.cpp @@ -717,7 +717,7 @@ void AddBotToGroupBoxController::shareBotGame(not_null chat) { } auto history = App::historyLoaded(chat); auto afterRequestId = history ? history->sendRequestId : 0; - auto randomId = rand_value(); + auto randomId = rand_value(); auto gameShortName = bot->botInfo->shareGameShortName; auto inputGame = MTP_inputGameShortName( bot->inputUser, @@ -764,7 +764,7 @@ void AddBotToGroupBoxController::addBotToGroup(not_null chat) { auto request = MTPmessages_StartBot( bot->inputUser, chat->input, - MTP_long(rand_value()), + MTP_long(rand_value()), MTP_string(info->startGroupToken)); auto done = App::main()->rpcDone( &MainWidget::sentUpdatesReceived); diff --git a/Telegram/SourceFiles/boxes/photo_crop_box.cpp b/Telegram/SourceFiles/boxes/photo_crop_box.cpp index 5c4bb2c89..e56224be6 100644 --- a/Telegram/SourceFiles/boxes/photo_crop_box.cpp +++ b/Telegram/SourceFiles/boxes/photo_crop_box.cpp @@ -56,7 +56,7 @@ void PhotoCropBox::prepare() { connect(this, SIGNAL(ready(const QImage&)), this, SLOT(onReady(const QImage&))); } - int32 s = st::boxWideWidth - st::boxPhotoPadding.left() - st::boxPhotoPadding.right(); + int32_t s = st::boxWideWidth - st::boxPhotoPadding.left() - st::boxPhotoPadding.right(); _thumb = App::pixmapFromImageInPlace(_img.scaled(s * cIntRetinaFactor(), s * cIntRetinaFactor(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); _thumb.setDevicePixelRatio(cRetinaFactor()); _mask = QImage(_thumb.size(), QImage::Format_ARGB32_Premultiplied); @@ -94,7 +94,7 @@ void PhotoCropBox::mousePressEvent(QMouseEvent *e) { int PhotoCropBox::mouseState(QPoint p) { p -= QPoint(_thumbx, _thumby); - int32 delta = st::cropPointSize, mdelta(-delta / 2); + int32_t delta = st::cropPointSize, mdelta(-delta / 2); if (QRect(_cropx + mdelta, _cropy + mdelta, delta, delta).contains(p)) { return 1; } else if (QRect(_cropx + _cropw + mdelta, _cropy + mdelta, delta, delta).contains(p)) { @@ -122,7 +122,7 @@ void PhotoCropBox::mouseMoveEvent(QMouseEvent *e) { } if (_downState) { if (_downState == 1) { - int32 dx = e->pos().x() - _fromposx, dy = e->pos().y() - _fromposy, d = (dx < dy) ? dx : dy; + int32_t dx = e->pos().x() - _fromposx, dy = e->pos().y() - _fromposy, d = (dx < dy) ? dx : dy; if (_fromcropx + d < 0) { d = -_fromcropx; } @@ -139,7 +139,7 @@ void PhotoCropBox::mouseMoveEvent(QMouseEvent *e) { update(); } } else if (_downState == 2) { - int32 dx = _fromposx - e->pos().x(), dy = e->pos().y() - _fromposy, d = (dx < dy) ? dx : dy; + int32_t dx = _fromposx - e->pos().x(), dy = e->pos().y() - _fromposy, d = (dx < dy) ? dx : dy; if (_fromcropx + _fromcropw - d > _thumbw) { d = _fromcropx + _fromcropw - _thumbw; } @@ -155,7 +155,7 @@ void PhotoCropBox::mouseMoveEvent(QMouseEvent *e) { update(); } } else if (_downState == 3) { - int32 dx = _fromposx - e->pos().x(), dy = _fromposy - e->pos().y(), d = (dx < dy) ? dx : dy; + int32_t dx = _fromposx - e->pos().x(), dy = _fromposy - e->pos().y(), d = (dx < dy) ? dx : dy; if (_fromcropx + _fromcropw - d > _thumbw) { d = _fromcropx + _fromcropw - _thumbw; } @@ -170,7 +170,7 @@ void PhotoCropBox::mouseMoveEvent(QMouseEvent *e) { update(); } } else if (_downState == 4) { - int32 dx = e->pos().x() - _fromposx, dy = _fromposy - e->pos().y(), d = (dx < dy) ? dx : dy; + int32_t dx = e->pos().x() - _fromposx, dy = _fromposy - e->pos().y(), d = (dx < dy) ? dx : dy; if (_fromcropx + d < 0) { d = -_fromcropx; } @@ -186,7 +186,7 @@ void PhotoCropBox::mouseMoveEvent(QMouseEvent *e) { update(); } } else if (_downState == 5) { - int32 dx = e->pos().x() - _fromposx, dy = e->pos().y() - _fromposy; + int32_t dx = e->pos().x() - _fromposx, dy = e->pos().y() - _fromposy; if (_fromcropx + dx < 0) { dx = -_fromcropx; } else if (_fromcropx + _fromcropw + dx > _thumbw) { @@ -204,7 +204,7 @@ void PhotoCropBox::mouseMoveEvent(QMouseEvent *e) { } } } - int32 cursorState = _downState ? _downState : mouseState(e->pos()); + int32_t cursorState = _downState ? _downState : mouseState(e->pos()); QCursor cur(style::cur_default); if (cursorState == 1 || cursorState == 3) { cur = style::cur_sizefdiag; @@ -260,8 +260,8 @@ void PhotoCropBox::sendPhoto() { if (_img.width() < _thumb.width()) { from = _thumb.toImage(); } - float64 x = float64(_cropx) / _thumbw, y = float64(_cropy) / _thumbh, w = float64(_cropw) / _thumbw; - int32 ix = int32(x * from.width()), iy = int32(y * from.height()), iw = int32(w * from.width()); + double x = double(_cropx) / _thumbw, y = double(_cropy) / _thumbh, w = double(_cropw) / _thumbw; + int32_t ix = int32_t(x * from.width()), iy = int32_t(y * from.height()), iw = int32_t(w * from.width()); if (ix < 0) { ix = 0; } @@ -274,7 +274,7 @@ void PhotoCropBox::sendPhoto() { if (iy + iw > from.height()) { iw = from.height() - iy; } - int32 offset = ix * from.depth() / 8 + iy * from.bytesPerLine(); + int32_t offset = ix * from.depth() / 8 + iy * from.bytesPerLine(); QImage cropped(from.constBits() + offset, iw, iw, from.bytesPerLine(), from.format()), tosend; if (from.format() == QImage::Format_Indexed8) { cropped.setColorCount(from.colorCount()); diff --git a/Telegram/SourceFiles/boxes/photo_crop_box.h b/Telegram/SourceFiles/boxes/photo_crop_box.h index 69a36f504..e94f4ea88 100644 --- a/Telegram/SourceFiles/boxes/photo_crop_box.h +++ b/Telegram/SourceFiles/boxes/photo_crop_box.h @@ -29,7 +29,7 @@ public: PhotoCropBox(QWidget*, const QImage &img, const PeerId &peer); PhotoCropBox(QWidget*, const QImage &img, PeerData *peer); - int32 mouseState(QPoint p); + int32_t mouseState(QPoint p); signals: void ready(const QImage &tosend); @@ -51,10 +51,10 @@ private: void sendPhoto(); QString _title; - int32 _downState = 0; - int32 _thumbx, _thumby, _thumbw, _thumbh; - int32 _cropx, _cropy, _cropw; - int32 _fromposx, _fromposy, _fromcropx, _fromcropy, _fromcropw; + int32_t _downState = 0; + int32_t _thumbx, _thumby, _thumbw, _thumbh; + int32_t _cropx, _cropy, _cropw; + int32_t _fromposx, _fromposy, _fromcropx, _fromcropy, _fromcropw; QImage _img; QPixmap _thumb; QImage _mask, _fade; diff --git a/Telegram/SourceFiles/boxes/rate_call_box.cpp b/Telegram/SourceFiles/boxes/rate_call_box.cpp index f562b4d7b..cccd47772 100644 --- a/Telegram/SourceFiles/boxes/rate_call_box.cpp +++ b/Telegram/SourceFiles/boxes/rate_call_box.cpp @@ -36,7 +36,7 @@ constexpr auto kMaxRating = 5; } // namespace -RateCallBox::RateCallBox(QWidget*, uint64 callId, uint64 callAccessHash) +RateCallBox::RateCallBox(QWidget*, uint64_t callId, uint64_t callAccessHash) : _callId(callId) , _callAccessHash(callAccessHash) { } diff --git a/Telegram/SourceFiles/boxes/rate_call_box.h b/Telegram/SourceFiles/boxes/rate_call_box.h index a4270828e..263cb48e5 100644 --- a/Telegram/SourceFiles/boxes/rate_call_box.h +++ b/Telegram/SourceFiles/boxes/rate_call_box.h @@ -33,7 +33,7 @@ class RateCallBox : public BoxContent, private MTP::Sender { Q_OBJECT public: - RateCallBox(QWidget*, uint64 callId, uint64 callAccessHash); + RateCallBox(QWidget*, uint64_t callId, uint64_t callAccessHash); private slots: void onSend(); @@ -52,8 +52,8 @@ private: void updateMaxHeight(); void ratingChanged(int value); - uint64 _callId = 0; - uint64 _callAccessHash = 0; + uint64_t _callId = 0; + uint64_t _callAccessHash = 0; int _rating = 0; std::vector> _stars; diff --git a/Telegram/SourceFiles/boxes/send_files_box.cpp b/Telegram/SourceFiles/boxes/send_files_box.cpp index 6f1068da2..846bb7254 100644 --- a/Telegram/SourceFiles/boxes/send_files_box.cpp +++ b/Telegram/SourceFiles/boxes/send_files_box.cpp @@ -112,9 +112,9 @@ void SendFilesBox::prepareSingleFileLayout() { _previewWidth = qMax(image.width(), kMinPreviewWidth); } auto maxthumbh = qMin(qRound(1.5 * _previewWidth), st::confirmMaxHeight); - _previewHeight = qRound(originalHeight * float64(_previewWidth) / originalWidth); + _previewHeight = qRound(originalHeight * double(_previewWidth) / originalWidth); if (_previewHeight > maxthumbh) { - _previewWidth = qRound(_previewWidth * float64(maxthumbh) / _previewHeight); + _previewWidth = qRound(_previewWidth * double(maxthumbh) / _previewHeight); accumulate_max(_previewWidth, kMinPreviewWidth); _previewHeight = maxthumbh; } @@ -374,7 +374,7 @@ void SendFilesBox::paintEvent(QPaintEvent *e) { linktop = st::msgFileThumbLinkTop; } auto namewidth = w - nameleft - (_fileThumb.isNull() ? st::msgFilePadding.left() : st::msgFileThumbPadding.left()); - int32 x = (width() - w) / 2, y = st::boxPhotoPadding.top(); + int32_t x = (width() - w) / 2, y = st::boxPhotoPadding.top(); App::roundRect(p, x, y, w, h, st::msgOutBg, MessageOutCorners, &st::msgOutShadow); @@ -493,7 +493,7 @@ EditCaptionBox::EditCaptionBox(QWidget*, HistoryMedia *media, FullMsgId msgId) : if (image->isNull()) { _thumbw = 0; } else { - int32 tw = image->width(), th = image->height(); + int32_t tw = image->width(), th = image->height(); if (tw > th) { _thumbw = (tw * st::msgFileThumbSize) / th; } else { @@ -515,10 +515,10 @@ EditCaptionBox::EditCaptionBox(QWidget*, HistoryMedia *media, FullMsgId msgId) : _isAudio = (doc->voice() || doc->song()); } } else { - int32 maxW = 0, maxH = 0; + int32_t maxW = 0, maxH = 0; if (_animated) { - int32 limitW = st::boxWideWidth - st::boxPhotoPadding.left() - st::boxPhotoPadding.right(); - int32 limitH = st::confirmMaxHeight; + int32_t limitW = st::boxWideWidth - st::boxPhotoPadding.left() - st::boxPhotoPadding.right(); + int32_t limitH = st::confirmMaxHeight; maxW = qMax(dimensions.width(), 1); maxH = qMax(dimensions.height(), 1); if (maxW * limitH > maxH * limitW) { @@ -539,7 +539,7 @@ EditCaptionBox::EditCaptionBox(QWidget*, HistoryMedia *media, FullMsgId msgId) : maxH = dimensions.height(); _thumb = image->pixNoCache(maxW * cIntRetinaFactor(), maxH * cIntRetinaFactor(), Images::Option::Smooth, maxW, maxH); } - int32 tw = _thumb.width(), th = _thumb.height(); + int32_t tw = _thumb.width(), th = _thumb.height(); if (!tw || !th) { tw = th = 1; } @@ -547,10 +547,10 @@ EditCaptionBox::EditCaptionBox(QWidget*, HistoryMedia *media, FullMsgId msgId) : if (_thumb.width() < _thumbw) { _thumbw = (_thumb.width() > 20) ? _thumb.width() : 20; } - int32 maxthumbh = qMin(qRound(1.5 * _thumbw), int(st::confirmMaxHeight)); - _thumbh = qRound(th * float64(_thumbw) / tw); + int32_t maxthumbh = qMin(qRound(1.5 * _thumbw), int(st::confirmMaxHeight)); + _thumbh = qRound(th * double(_thumbw) / tw); if (_thumbh > maxthumbh) { - _thumbw = qRound(_thumbw * float64(maxthumbh) / _thumbh); + _thumbw = qRound(_thumbw * double(maxthumbh) / _thumbh); _thumbh = maxthumbh; if (_thumbw < 10) { _thumbw = 10; @@ -677,9 +677,9 @@ void EditCaptionBox::paintEvent(QPaintEvent *e) { icon->paintInCenter(p, inner); } } else if (_doc) { - int32 w = width() - st::boxPhotoPadding.left() - st::boxPhotoPadding.right(); - int32 h = _thumbw ? (0 + st::msgFileThumbSize + 0) : (0 + st::msgFileSize + 0); - int32 nameleft = 0, nametop = 0, nameright = 0, statustop = 0; + int32_t w = width() - st::boxPhotoPadding.left() - st::boxPhotoPadding.right(); + int32_t h = _thumbw ? (0 + st::msgFileThumbSize + 0) : (0 + st::msgFileSize + 0); + int32_t nameleft = 0, nametop = 0, nameright = 0, statustop = 0; if (_thumbw) { nameleft = 0 + st::msgFileThumbSize + st::msgFileThumbPadding.right(); nametop = st::msgFileThumbNameTop - st::msgFileThumbPadding.top(); @@ -691,12 +691,12 @@ void EditCaptionBox::paintEvent(QPaintEvent *e) { nameright = 0; statustop = st::msgFileStatusTop - st::msgFilePadding.top(); } - int32 namewidth = w - nameleft - 0; + int32_t namewidth = w - nameleft - 0; if (namewidth > _statusw) { //w -= (namewidth - _statusw); //namewidth = _statusw; } - int32 x = (width() - w) / 2, y = st::boxPhotoPadding.top(); + int32_t x = (width() - w) / 2, y = st::boxPhotoPadding.top(); // App::roundRect(p, x, y, w, h, st::msgInBg, MessageInCorners, &st::msgInShadow); diff --git a/Telegram/SourceFiles/boxes/sessions_box.cpp b/Telegram/SourceFiles/boxes/sessions_box.cpp index 48cda4d77..6d8c98312 100644 --- a/Telegram/SourceFiles/boxes/sessions_box.cpp +++ b/Telegram/SourceFiles/boxes/sessions_box.cpp @@ -115,7 +115,7 @@ void SessionsBox::gotAuthorizations(const MTPaccount_Authorizations &result) { // deviceModel = qsl("Linux"); // } if (appVer == QString::number(appVer.toInt())) { - int32 ver = appVer.toInt(); + int32_t ver = appVer.toInt(); appVer = QString("%1.%2").arg(ver / 1000000).arg((ver % 1000000) / 1000) + ((ver % 1000) ? ('.' + QString::number(ver % 1000)) : QString()); //} else { // appVer = QString(); @@ -140,7 +140,7 @@ void SessionsBox::gotAuthorizations(const MTPaccount_Authorizations &result) { if (!data.hash || (d.vflags.v & 1)) { data.active = lang(lng_sessions_header); data.activeWidth = st::sessionWhenFont->width(lang(lng_sessions_header)); - int32 availForName = availCurrent - st::sessionPadding.right() - data.activeWidth; + int32_t availForName = availCurrent - st::sessionPadding.right() - data.activeWidth; if (data.nameWidth > availForName) { data.name = st::sessionNameFont->elided(data.name, availForName); data.nameWidth = st::sessionNameFont->width(data.name); @@ -168,7 +168,7 @@ void SessionsBox::gotAuthorizations(const MTPaccount_Authorizations &result) { data.active = lastDate.toString(qsl("d.MM.yy")); } data.activeWidth = st::sessionWhenFont->width(data.active); - int32 availForName = availOther - st::sessionPadding.right() - data.activeWidth; + int32_t availForName = availOther - st::sessionPadding.right() - data.activeWidth; if (data.nameWidth > availForName) { data.name = st::sessionNameFont->elided(data.name, availForName); data.nameWidth = st::sessionNameFont->width(data.name); @@ -185,7 +185,7 @@ void SessionsBox::gotAuthorizations(const MTPaccount_Authorizations &result) { } _list.push_back(data); - for (int32 i = _list.size(); i > 1;) { + for (int32_t i = _list.size(); i > 1;) { --i; if (_list.at(i).activeTime > _list.at(i - 1).activeTime) { qSwap(_list[i], _list[i - 1]); @@ -242,8 +242,8 @@ void SessionsBox::Inner::paintEvent(QPaintEvent *e) { Painter p(this); p.fillRect(r, st::boxBg); - int32 x = st::sessionPadding.left(), xact = st::sessionTerminateSkip + st::sessionTerminate.iconPosition.x();// st::sessionTerminateSkip + st::sessionTerminate.width + st::sessionTerminateSkip; - int32 w = width(); + int32_t x = st::sessionPadding.left(), xact = st::sessionTerminateSkip + st::sessionTerminate.iconPosition.x();// st::sessionTerminateSkip + st::sessionTerminate.width + st::sessionTerminateSkip; + int32_t w = width(); if (_current->active.isEmpty() && _list->isEmpty()) { p.setFont(st::noContactsFont->f); @@ -277,11 +277,11 @@ void SessionsBox::Inner::paintEvent(QPaintEvent *e) { } p.setFont(st::linkFont->f); - int32 count = _list->size(); - int32 from = floorclamp(r.y() - st::sessionCurrentHeight, st::sessionHeight, 0, count); - int32 to = ceilclamp(r.y() + r.height() - st::sessionCurrentHeight, st::sessionHeight, 0, count); + int32_t count = _list->size(); + int32_t from = floorclamp(r.y() - st::sessionCurrentHeight, st::sessionHeight, 0, count); + int32_t to = ceilclamp(r.y() + r.height() - st::sessionCurrentHeight, st::sessionHeight, 0, count); p.translate(0, from * st::sessionHeight); - for (int32 i = from; i < to; ++i) { + for (int32_t i = from; i < to; ++i) { const SessionsBox::Data &auth(_list->at(i)); p.setFont(st::sessionNameFont); @@ -334,8 +334,8 @@ void SessionsBox::Inner::onTerminateAll() { })), KeepOtherLayers); } -void SessionsBox::Inner::terminateDone(uint64 hash, const MTPBool &result) { - for (int32 i = 0, l = _list->size(); i < l; ++i) { +void SessionsBox::Inner::terminateDone(uint64_t hash, const MTPBool &result) { + for (int32_t i = 0, l = _list->size(); i < l; ++i) { if (_list->at(i).hash == hash) { _list->removeAt(i); break; @@ -345,7 +345,7 @@ void SessionsBox::Inner::terminateDone(uint64 hash, const MTPBool &result) { emit oneTerminated(); } -bool SessionsBox::Inner::terminateFail(uint64 hash, const RPCError &error) { +bool SessionsBox::Inner::terminateFail(uint64_t hash, const RPCError &error) { if (MTP::isDefaultHandledError(error)) return false; TerminateButtons::iterator i = _terminateButtons.find(hash); @@ -379,7 +379,7 @@ void SessionsBox::Inner::listUpdated() { for (TerminateButtons::iterator i = _terminateButtons.begin(), e = _terminateButtons.end(); i != e; ++i) { i.value()->move(0, -1); } - for (int32 i = 0, l = _list->size(); i < l; ++i) { + for (int32_t i = 0, l = _list->size(); i < l; ++i) { TerminateButtons::iterator j = _terminateButtons.find(_list->at(i).hash); if (j == _terminateButtons.cend()) { j = _terminateButtons.insert(_list->at(i).hash, new Ui::IconButton(this, st::sessionTerminate)); diff --git a/Telegram/SourceFiles/boxes/sessions_box.h b/Telegram/SourceFiles/boxes/sessions_box.h index 707b06bd5..dff7068dd 100644 --- a/Telegram/SourceFiles/boxes/sessions_box.h +++ b/Telegram/SourceFiles/boxes/sessions_box.h @@ -52,10 +52,10 @@ private slots: private: void setLoading(bool loading); struct Data { - uint64 hash; + uint64_t hash; - int32 activeTime; - int32 nameWidth, activeWidth, infoWidth, ipWidth; + int32_t activeTime; + int32_t nameWidth, activeWidth, infoWidth, ipWidth; QString name, active, info, ip; }; using List = QList; @@ -98,8 +98,8 @@ public slots: void onTerminateAll(); private: - void terminateDone(uint64 hash, const MTPBool &result); - bool terminateFail(uint64 hash, const RPCError &error); + void terminateDone(uint64_t hash, const MTPBool &result); + bool terminateFail(uint64_t hash, const RPCError &error); void terminateAllDone(const MTPBool &res); bool terminateAllFail(const RPCError &error); @@ -107,7 +107,7 @@ private: SessionsBox::List *_list; SessionsBox::Data *_current; - typedef QMap TerminateButtons; + typedef QMap TerminateButtons; TerminateButtons _terminateButtons; object_ptr _terminateAll; diff --git a/Telegram/SourceFiles/boxes/share_box.cpp b/Telegram/SourceFiles/boxes/share_box.cpp index 0936070e5..1a9e475f7 100644 --- a/Telegram/SourceFiles/boxes/share_box.cpp +++ b/Telegram/SourceFiles/boxes/share_box.cpp @@ -64,7 +64,7 @@ void ShareBox::prepare() { setDimensions(st::boxWideWidth, st::boxMaxListHeight); _select->setQueryChangedCallback([this](const QString &query) { onFilterUpdate(query); }); - _select->setItemRemovedCallback([this](uint64 itemId) { + _select->setItemRemovedCallback([this](uint64_t itemId) { if (auto peer = App::peerLoaded(itemId)) { _inner->peerUnselected(peer); onSelectedChanged(); @@ -481,7 +481,7 @@ ShareBox::Inner::Chat *ShareBox::Inner::getChat(Dialogs::Row *row) { void ShareBox::Inner::setActive(int active) { if (active != _active) { - auto changeNameFg = [this](int index, float64 from, float64 to) { + auto changeNameFg = [this](int index, double from, double to) { if (auto chat = getChatAtIndex(index)) { chat->nameActive.start([this, peer = chat->peer] { repaintChat(peer); @@ -620,7 +620,7 @@ void ShareBox::Inner::onSelectActive() { } void ShareBox::Inner::resizeEvent(QResizeEvent *e) { - _columnSkip = (width() - _columnCount * st::sharePhotoCheckbox.imageRadius * 2) / float64(_columnCount + 1); + _columnSkip = (width() - _columnCount * st::sharePhotoCheckbox.imageRadius * 2) / double(_columnCount + 1); _rowWidthReal = st::sharePhotoCheckbox.imageRadius * 2 + _columnSkip; _rowsLeft = qFloor(_columnSkip / 2); _rowWidth = qFloor(_rowWidthReal); @@ -743,7 +743,7 @@ void ShareBox::Inner::updateFilter(QString filter) { void ShareBox::Inner::peopleReceived(const QString &query, const QVector &people) { _lastQuery = query.toLower().trimmed(); if (_lastQuery.at(0) == '@') _lastQuery = _lastQuery.mid(1); - int32 already = _byUsernameFiltered.size(); + int32_t already = _byUsernameFiltered.size(); _byUsernameFiltered.reserve(already + people.size()); d_byUsernameFiltered.reserve(already + people.size()); for_const (auto &mtpPeer, people) { @@ -800,10 +800,10 @@ QVector ShareBox::Inner::selected() const { QString AppendShareGameScoreUrl(const QString &url, const FullMsgId &fullId) { auto shareHashData = QByteArray(0x10, Qt::Uninitialized); - auto shareHashDataInts = reinterpret_cast(shareHashData.data()); + auto shareHashDataInts = reinterpret_cast(shareHashData.data()); auto channel = fullId.channel ? App::channelLoaded(fullId.channel) : static_cast(nullptr); auto channelAccessHash = channel ? channel->access : 0ULL; - auto channelAccessHashInts = reinterpret_cast(&channelAccessHash); + auto channelAccessHashInts = reinterpret_cast(&channelAccessHash); shareHashDataInts[0] = Auth().userId(); shareHashDataInts[1] = fullId.channel; shareHashDataInts[2] = fullId.msg; @@ -815,7 +815,7 @@ QString AppendShareGameScoreUrl(const QString &url, const FullMsgId &fullId) { hashSha1(shareHashData.constData(), shareHashData.size(), shareHashEncrypted.data()); // Mix in channel access hash to the first 64 bits of SHA1 of data. - *reinterpret_cast(shareHashEncrypted.data()) ^= *reinterpret_cast(channelAccessHashInts); + *reinterpret_cast(shareHashEncrypted.data()) ^= *reinterpret_cast(channelAccessHashInts); // Encrypt data. if (!Local::encrypt(shareHashData.constData(), shareHashEncrypted.data() + key128Size, shareHashData.size(), shareHashEncrypted.constData())) { @@ -861,7 +861,7 @@ void ShareGameScoreByHash(const QString &hash) { hashSha1(hashData.constData(), hashData.size(), dataSha1); // Mix out channel access hash from the first 64 bits of SHA1 of data. - auto channelAccessHash = *reinterpret_cast(hashEncrypted.data()) ^ *reinterpret_cast(dataSha1); + auto channelAccessHash = *reinterpret_cast(hashEncrypted.data()) ^ *reinterpret_cast(dataSha1); // Check next 64 bits of SHA1() of data. auto skipSha1Part = sizeof(channelAccessHash); @@ -870,14 +870,14 @@ void ShareGameScoreByHash(const QString &hash) { return; } - auto hashDataInts = reinterpret_cast(hashData.data()); + auto hashDataInts = reinterpret_cast(hashData.data()); if (!AuthSession::Exists() || hashDataInts[0] != Auth().userId()) { Ui::show(Box(lang(lng_share_wrong_user))); return; } // Check first 32 bits of channel access hash. - auto channelAccessHashInts = reinterpret_cast(&channelAccessHash); + auto channelAccessHashInts = reinterpret_cast(&channelAccessHash); if (channelAccessHashInts[0] != hashDataInts[3]) { Ui::show(Box(lang(lng_share_wrong_user))); return; diff --git a/Telegram/SourceFiles/boxes/share_box.h b/Telegram/SourceFiles/boxes/share_box.h index b4861b279..6caf6cb1d 100644 --- a/Telegram/SourceFiles/boxes/share_box.h +++ b/Telegram/SourceFiles/boxes/share_box.h @@ -182,8 +182,8 @@ private: void refresh(); - float64 _columnSkip = 0.; - float64 _rowWidthReal = 0.; + double _columnSkip = 0.; + double _rowWidthReal = 0.; int _rowsLeft = 0; int _rowsTop = 0; int _rowWidth = 0; diff --git a/Telegram/SourceFiles/boxes/sticker_set_box.cpp b/Telegram/SourceFiles/boxes/sticker_set_box.cpp index 087f8a5d0..26f033165 100644 --- a/Telegram/SourceFiles/boxes/sticker_set_box.cpp +++ b/Telegram/SourceFiles/boxes/sticker_set_box.cpp @@ -56,10 +56,10 @@ void StickerSetBox::prepare() { onUpdateButtons(); connect(_inner, SIGNAL(updateButtons()), this, SLOT(onUpdateButtons())); - connect(_inner, SIGNAL(installed(uint64)), this, SLOT(onInstalled(uint64))); + connect(_inner, SIGNAL(installed(uint64_t)), this, SLOT(onInstalled(uint64_t))); } -void StickerSetBox::onInstalled(uint64 setId) { +void StickerSetBox::onInstalled(uint64_t setId) { emit installed(setId); closeBox(); } @@ -180,7 +180,7 @@ void StickerSetBox::Inner::gotSet(const MTPmessages_StickerSet &set) { if (_pack.isEmpty()) { Ui::show(Box(lang(lng_stickers_not_found))); } else { - int32 rows = _pack.size() / kStickersPanelPerRow + ((_pack.size() % kStickersPanelPerRow) ? 1 : 0); + int32_t rows = _pack.size() / kStickersPanelPerRow + ((_pack.size() % kStickersPanelPerRow) ? 1 : 0); resize(st::stickersPadding.left() + kStickersPanelPerRow * st::stickersSize.width(), st::stickersPadding.top() + rows * st::stickersSize.height() + st::stickersPadding.bottom()); } _loaded = true; @@ -315,7 +315,7 @@ void StickerSetBox::Inner::setSelected(int selected) { } } -void StickerSetBox::Inner::startOverAnimation(int index, float64 from, float64 to) { +void StickerSetBox::Inner::startOverAnimation(int index, double from, double to) { if (index >= 0 && index < _packOvers.size()) { _packOvers[index].start([this, index] { int row = index / kStickersPanelPerRow; @@ -335,13 +335,13 @@ void StickerSetBox::Inner::onPreview() { } } -int32 StickerSetBox::Inner::stickerFromGlobalPos(const QPoint &p) const { +int32_t StickerSetBox::Inner::stickerFromGlobalPos(const QPoint &p) const { QPoint l(mapFromGlobal(p)); if (rtl()) l.setX(width() - l.x()); - int32 row = (l.y() >= st::stickersPadding.top()) ? qFloor((l.y() - st::stickersPadding.top()) / st::stickersSize.height()) : -1; - int32 col = (l.x() >= st::stickersPadding.left()) ? qFloor((l.x() - st::stickersPadding.left()) / st::stickersSize.width()) : -1; + int32_t row = (l.y() >= st::stickersPadding.top()) ? qFloor((l.y() - st::stickersPadding.top()) / st::stickersSize.height()) : -1; + int32_t col = (l.x() >= st::stickersPadding.left()) ? qFloor((l.x() - st::stickersPadding.left()) / st::stickersSize.width()) : -1; if (row >= 0 && col >= 0 && col < kStickersPanelPerRow) { - int32 result = row * kStickersPanelPerRow + col; + int32_t result = row * kStickersPanelPerRow + col; return (result < _pack.size()) ? result : -1; } return -1; @@ -354,12 +354,12 @@ void StickerSetBox::Inner::paintEvent(QPaintEvent *e) { if (_pack.isEmpty()) return; auto ms = getms(); - int32 rows = _pack.size() / kStickersPanelPerRow + ((_pack.size() % kStickersPanelPerRow) ? 1 : 0); - int32 from = qFloor(e->rect().top() / st::stickersSize.height()), to = qFloor(e->rect().bottom() / st::stickersSize.height()) + 1; + int32_t rows = _pack.size() / kStickersPanelPerRow + ((_pack.size() % kStickersPanelPerRow) ? 1 : 0); + int32_t from = qFloor(e->rect().top() / st::stickersSize.height()), to = qFloor(e->rect().bottom() / st::stickersSize.height()) + 1; - for (int32 i = from; i < to; ++i) { - for (int32 j = 0; j < kStickersPanelPerRow; ++j) { - int32 index = i * kStickersPanelPerRow + j; + for (int32_t i = from; i < to; ++i) { + for (int32_t j = 0; j < kStickersPanelPerRow; ++j) { + int32_t index = i * kStickersPanelPerRow + j; if (index >= _pack.size()) break; Assert(index < _packOvers.size()); @@ -386,9 +386,9 @@ void StickerSetBox::Inner::paintEvent(QPaintEvent *e) { } } - float64 coef = qMin((st::stickersSize.width() - st::buttonRadius * 2) / float64(doc->dimensions.width()), (st::stickersSize.height() - st::buttonRadius * 2) / float64(doc->dimensions.height())); + double coef = qMin((st::stickersSize.width() - st::buttonRadius * 2) / double(doc->dimensions.width()), (st::stickersSize.height() - st::buttonRadius * 2) / double(doc->dimensions.height())); if (coef > 1) coef = 1; - int32 w = qRound(coef * doc->dimensions.width()), h = qRound(coef * doc->dimensions.height()); + int32_t w = qRound(coef * doc->dimensions.width()), h = qRound(coef * doc->dimensions.height()); if (w < 1) w = 1; if (h < 1) h = 1; QPoint ppos = pos + QPoint((st::stickersSize.width() - w) / 2, (st::stickersSize.height() - h) / 2); @@ -410,7 +410,7 @@ bool StickerSetBox::Inner::loaded() const { return _loaded && !_pack.isEmpty(); } -int32 StickerSetBox::Inner::notInstalled() const { +int32_t StickerSetBox::Inner::notInstalled() const { if (!_loaded) return 0; auto it = Global::StickerSets().constFind(_setId); if (it == Global::StickerSets().cend() || !(it->flags & MTPDstickerSet::Flag::f_installed) || (it->flags & MTPDstickerSet::Flag::f_archived)) return _pack.size(); diff --git a/Telegram/SourceFiles/boxes/sticker_set_box.h b/Telegram/SourceFiles/boxes/sticker_set_box.h index 064f5abab..5283095c9 100644 --- a/Telegram/SourceFiles/boxes/sticker_set_box.h +++ b/Telegram/SourceFiles/boxes/sticker_set_box.h @@ -36,7 +36,7 @@ public: StickerSetBox(QWidget*, const MTPInputStickerSet &set); signals: - void installed(uint64 id); + void installed(uint64_t id); protected: void prepare() override; @@ -48,7 +48,7 @@ private slots: void onShareStickers(); void onUpdateButtons(); - void onInstalled(uint64 id); + void onInstalled(uint64_t id); private: void updateButtons(); @@ -68,7 +68,7 @@ public: Inner(QWidget *parent, const MTPInputStickerSet &set); bool loaded() const; - int32 notInstalled() const; + int32_t notInstalled() const; bool official() const; base::lambda title() const; QString shortName() const; @@ -90,12 +90,12 @@ private slots: signals: void updateButtons(); - void installed(uint64 id); + void installed(uint64_t id); private: void updateSelected(); void setSelected(int selected); - void startOverAnimation(int index, float64 from, float64 to); + void startOverAnimation(int index, double from, double to); int stickerFromGlobalPos(const QPoint &p) const; void gotSet(const MTPmessages_StickerSet &set); @@ -112,11 +112,11 @@ private: StickerPack _pack; StickersByEmojiMap _emoji; bool _loaded = false; - uint64 _setId = 0; - uint64 _setAccess = 0; + uint64_t _setId = 0; + uint64_t _setAccess = 0; QString _setTitle, _setShortName; - int32 _setCount = 0; - int32 _setHash = 0; + int32_t _setCount = 0; + int32_t _setHash = 0; MTPDstickerSet::Flags _setFlags = 0; int _visibleTop = 0; diff --git a/Telegram/SourceFiles/boxes/stickers_box.cpp b/Telegram/SourceFiles/boxes/stickers_box.cpp index 98779482a..6132e5844 100644 --- a/Telegram/SourceFiles/boxes/stickers_box.cpp +++ b/Telegram/SourceFiles/boxes/stickers_box.cpp @@ -156,7 +156,7 @@ StickersBox::StickersBox(QWidget*, not_null megagroup) subscribe(_installed.widget()->scrollToY, [this](int y) { onScrollToY(y); }); } -void StickersBox::getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedStickers &result) { +void StickersBox::getArchivedDone(uint64_t offsetId, const MTPmessages_ArchivedStickers &result) { _archivedRequestId = 0; _archivedLoaded = true; if (result.type() != mtpc_messages_archivedStickers) { @@ -253,10 +253,10 @@ void StickersBox::prepare() { if (_archived.widget() && _section != Section::Archived) _archived.widget()->hide(); if (_featured.widget()) { - _featured.widget()->setInstallSetCallback([this](uint64 setId) { installSet(setId); }); + _featured.widget()->setInstallSetCallback([this](uint64_t setId) { installSet(setId); }); } if (_archived.widget()) { - _archived.widget()->setInstallSetCallback([this](uint64 setId) { installSet(setId); }); + _archived.widget()->setInstallSetCallback([this](uint64_t setId) { installSet(setId); }); _archived.widget()->setLoadMoreCallback([this] { loadMoreArchived(); }); } @@ -326,7 +326,7 @@ void StickersBox::loadMoreArchived() { return; } - uint64 lastId = 0; + uint64_t lastId = 0; for (auto setIt = Global::ArchivedStickerSetsOrder().cend(), e = Global::ArchivedStickerSetsOrder().cbegin(); setIt != e;) { --setIt; auto it = Global::StickerSets().constFind(*setIt); @@ -441,7 +441,7 @@ QPixmap StickersBox::grabContentCache() { return result; } -void StickersBox::installSet(uint64 setId) { +void StickersBox::installSet(uint64_t setId) { auto &sets = Global::RefStickerSets(); auto it = sets.find(setId); if (it == sets.cend()) { @@ -468,7 +468,7 @@ void StickersBox::installDone(const MTPmessages_StickerSetInstallResult &result) } } -bool StickersBox::installFail(uint64 setId, const RPCError &error) { +bool StickersBox::installFail(uint64_t setId, const RPCError &error) { if (MTP::isDefaultHandledError(error)) return false; auto &sets = Global::RefStickerSets(); @@ -568,7 +568,7 @@ void StickersBox::setInnerFocus() { StickersBox::~StickersBox() = default; -StickersBox::Inner::Row::Row(uint64 id, DocumentData *sticker, int32 count, const QString &title, int titleWidth, bool installed, bool official, bool unread, bool archived, bool removed, int32 pixw, int32 pixh) : id(id) +StickersBox::Inner::Row::Row(uint64_t id, DocumentData *sticker, int32_t count, const QString &title, int titleWidth, bool installed, bool official, bool unread, bool archived, bool removed, int32_t pixw, int32_t pixh) : id(id) , sticker(sticker) , count(count) , title(title) @@ -654,11 +654,11 @@ void StickersBox::Inner::paintEvent(QPaintEvent *e) { } else { p.translate(0, _itemsTop); - int32 yFrom = clip.y() - _itemsTop, yTo = clip.y() + clip.height() - _itemsTop; - int32 from = floorclamp(yFrom - _rowHeight, _rowHeight, 0, _rows.size()); - int32 to = ceilclamp(yTo + _rowHeight, _rowHeight, 0, _rows.size()); + int32_t yFrom = clip.y() - _itemsTop, yTo = clip.y() + clip.height() - _itemsTop; + int32_t from = floorclamp(yFrom - _rowHeight, _rowHeight, 0, _rows.size()); + int32_t to = ceilclamp(yTo + _rowHeight, _rowHeight, 0, _rows.size()); p.translate(0, from * _rowHeight); - for (int32 i = from; i < to; ++i) { + for (int32_t i = from; i < to; ++i) { if (i != _above) { paintRow(p, _rows[i].get(), i, ms); } @@ -957,14 +957,14 @@ void StickersBox::Inner::onUpdateSelected() { } if (_dragStart.y() > local.y() && _dragging > 0) { shift = -floorclamp(_dragStart.y() - local.y() + (_rowHeight / 2), _rowHeight, 0, _dragging - firstSetIndex); - for (int32 from = _dragging, to = _dragging + shift; from > to; --from) { + for (int32_t from = _dragging, to = _dragging + shift; from > to; --from) { qSwap(_rows[from], _rows[from - 1]); _rows[from]->yadd = anim::value(_rows[from]->yadd.current() - _rowHeight, 0); _animStartTimes[from] = ms; } } else if (_dragStart.y() < local.y() && _dragging + 1 < _rows.size()) { shift = floorclamp(local.y() - _dragStart.y() + (_rowHeight / 2), _rowHeight, 0, _rows.size() - _dragging - 1); - for (int32 from = _dragging, to = _dragging + shift; from < to; ++from) { + for (int32_t from = _dragging, to = _dragging + shift; from < to; ++from) { qSwap(_rows[from], _rows[from + 1]); _rows[from]->yadd = anim::value(_rows[from]->yadd.current() + _rowHeight, 0); _animStartTimes[from] = ms; @@ -1033,7 +1033,7 @@ void StickersBox::Inner::onUpdateSelected() { } } -float64 StickersBox::Inner::aboveShadowOpacity() const { +double StickersBox::Inner::aboveShadowOpacity() const { if (_above < 0) return 0; auto dx = 0; @@ -1126,7 +1126,7 @@ void StickersBox::Inner::step_shifting(TimeMs ms, bool timer) { if (updateMin < 0) updateMin = i; updateMax = i; if (start + st::stickersRowDuration > ms && ms >= start) { - _rows[i]->yadd.update(float64(ms - start) / st::stickersRowDuration, anim::sineInOut); + _rows[i]->yadd.update(double(ms - start) / st::stickersRowDuration, anim::sineInOut); animating = true; } else { _rows[i]->yadd.finish(); @@ -1138,7 +1138,7 @@ void StickersBox::Inner::step_shifting(TimeMs ms, bool timer) { if (updateMin < 0 || updateMin > _above) updateMin = _above; if (updateMax < _above) updateMin = _above; if (_aboveShadowFadeStart + st::stickersRowDuration > ms && ms > _aboveShadowFadeStart) { - _aboveShadowFadeOpacity.update(float64(ms - _aboveShadowFadeStart) / st::stickersRowDuration, anim::sineInOut); + _aboveShadowFadeOpacity.update(double(ms - _aboveShadowFadeStart) / st::stickersRowDuration, anim::sineInOut); animating = true; } else { _aboveShadowFadeOpacity.finish(); @@ -1179,7 +1179,7 @@ void StickersBox::Inner::clear() { update(); } -void StickersBox::Inner::setActionSel(int32 actionSel) { +void StickersBox::Inner::setActionSel(int32_t actionSel) { if (actionSel != _actionSel) { if (_actionSel >= 0) update(0, _itemsTop + _actionSel * _rowHeight, width(), _rowHeight); _actionSel = actionSel; @@ -1502,7 +1502,7 @@ Stickers::Order StickersBox::Inner::getRemovedSets() const { }); } -int StickersBox::Inner::getRowIndex(uint64 setId) const { +int StickersBox::Inner::getRowIndex(uint64_t setId) const { for (auto i = 0, count = int(_rows.size()); i != count; ++i) { auto &row = _rows[i]; if (row->id == setId) { diff --git a/Telegram/SourceFiles/boxes/stickers_box.h b/Telegram/SourceFiles/boxes/stickers_box.h index 9323eeb90..766a1456c 100644 --- a/Telegram/SourceFiles/boxes/stickers_box.h +++ b/Telegram/SourceFiles/boxes/stickers_box.h @@ -96,19 +96,19 @@ private: void rebuildList(Tab *tab = nullptr); void updateTabsGeometry(); void switchTab(); - void installSet(uint64 setId); + void installSet(uint64_t setId); int getTopSkip() const; void saveChanges(); QPixmap grabContentCache(); void installDone(const MTPmessages_StickerSetInstallResult &result); - bool installFail(uint64 setId, const RPCError &error); + bool installFail(uint64_t setId, const RPCError &error); void preloadArchivedSets(); void requestArchivedSets(); void loadMoreArchived(); - void getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedStickers &result); + void getArchivedDone(uint64_t offsetId, const MTPmessages_ArchivedStickers &result); object_ptr _tabs = { nullptr }; QList
_tabIndices; @@ -166,7 +166,7 @@ public: void setFullOrder(const Stickers::Order &order); void setRemovedSets(const Stickers::Order &removed); - void setInstallSetCallback(base::lambda callback) { + void setInstallSetCallback(base::lambda callback) { _installSetCallback = std::move(callback); } void setLoadMoreCallback(base::lambda callback) { @@ -199,15 +199,15 @@ public slots: private: struct Row { - Row(uint64 id, DocumentData *sticker, int32 count, const QString &title, int titleWidth, bool installed, bool official, bool unread, bool archived, bool removed, int32 pixw, int32 pixh); + Row(uint64_t id, DocumentData *sticker, int32_t count, const QString &title, int titleWidth, bool installed, bool official, bool unread, bool archived, bool removed, int32_t pixw, int32_t pixh); bool isRecentSet() const { return (id == Stickers::CloudRecentSetId); } ~Row(); - uint64 id = 0; + uint64_t id = 0; DocumentData *sticker = nullptr; - int32 count = 0; + int32_t count = 0; QString title; int titleWidth = 0; bool installed = false; @@ -215,8 +215,8 @@ private: bool unread = false; bool archived = false; bool removed = false; - int32 pixw = 0; - int32 pixh = 0; + int32_t pixw = 0; + int32_t pixh = 0; anim::value yadd; std::unique_ptr ripple; }; @@ -226,7 +226,7 @@ private: void checkLoadMore(); void updateScrollbarWidth(); - int getRowIndex(uint64 setId) const; + int getRowIndex(uint64_t setId) const; void setRowRemoved(int index, bool removed); void setSelected(int selected); @@ -240,8 +240,8 @@ private: void paintRow(Painter &p, Row *set, int index, TimeMs ms); void paintFakeButton(Painter &p, Row *set, int index, TimeMs ms); void clear(); - void setActionSel(int32 actionSel); - float64 aboveShadowOpacity() const; + void setActionSel(int32_t actionSel); + double aboveShadowOpacity() const; void readVisibleSets(); @@ -259,7 +259,7 @@ private: Section _section; - int32 _rowHeight; + int32_t _rowHeight; std::vector> _rows; QList _animStartTimes; @@ -267,7 +267,7 @@ private: anim::value _aboveShadowFadeOpacity; BasicAnimation _a_shifting; - base::lambda _installSetCallback; + base::lambda _installSetCallback; base::lambda _loadMoreCallback; int _visibleTop = 0; diff --git a/Telegram/SourceFiles/boxes/username_box.cpp b/Telegram/SourceFiles/boxes/username_box.cpp index 013ef5b6b..6cbbd8f53 100644 --- a/Telegram/SourceFiles/boxes/username_box.cpp +++ b/Telegram/SourceFiles/boxes/username_box.cpp @@ -79,10 +79,10 @@ void UsernameBox::paintEvent(QPaintEvent *e) { p.drawTextLeft(st::usernamePadding.left(), _username->y() + _username->height() + ((st::usernameSkip - st::boxTextFont->height) / 2), width(), lang(lng_username_choose)); } p.setPen(st::boxTextFg); - int32 availw = st::boxWidth - st::usernamePadding.left(), h = _about.countHeight(availw); + int32_t availw = st::boxWidth - st::usernamePadding.left(), h = _about.countHeight(availw); _about.drawLeft(p, st::usernamePadding.left(), _username->y() + _username->height() + st::usernameSkip, availw, width()); - int32 linky = _username->y() + _username->height() + st::usernameSkip + h + st::usernameTextStyle.lineHeight + ((st::usernameTextStyle.lineHeight - st::boxTextFont->height) / 2); + int32_t linky = _username->y() + _username->height() + st::usernameSkip + h + st::usernameTextStyle.lineHeight + ((st::usernameTextStyle.lineHeight - st::boxTextFont->height) / 2); if (_link->isHidden()) { p.drawTextLeft(st::usernamePadding.left(), linky, width(), lang(lng_username_link_willbe)); p.setPen(st::usernameDefaultFg); @@ -98,8 +98,8 @@ void UsernameBox::resizeEvent(QResizeEvent *e) { _username->resize(width() - st::usernamePadding.left() - st::usernamePadding.right(), _username->height()); _username->moveToLeft(st::usernamePadding.left(), st::usernamePadding.top()); - int32 availw = st::boxWidth - st::usernamePadding.left(), h = _about.countHeight(availw); - int32 linky = _username->y() + _username->height() + st::usernameSkip + h + st::usernameTextStyle.lineHeight + ((st::usernameTextStyle.lineHeight - st::boxTextFont->height) / 2); + int32_t availw = st::boxWidth - st::usernamePadding.left(), h = _about.countHeight(availw); + int32_t linky = _username->y() + _username->height() + st::usernameSkip + h + st::usernameTextStyle.lineHeight + ((st::usernameTextStyle.lineHeight - st::boxTextFont->height) / 2); _link->moveToLeft(st::usernamePadding.left(), linky + st::usernameTextStyle.lineHeight + ((st::usernameTextStyle.lineHeight - st::boxTextFont->height) / 2)); } @@ -131,8 +131,8 @@ void UsernameBox::onChanged() { } _checkTimer->stop(); } else { - int32 len = name.size(); - for (int32 i = 0; i < len; ++i) { + int32_t len = name.size(); + for (int32_t i = 0; i < len; ++i) { QChar ch = name.at(i); if ((ch < 'A' || ch > 'Z') && (ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') && ch != '_' && (ch != '@' || i > 0)) { if (_errorText != lang(lng_username_bad_symbols)) { @@ -243,4 +243,4 @@ void UsernameBox::updateLinkText() { update(); } } -} \ No newline at end of file +} diff --git a/Telegram/SourceFiles/calls/calls_call.cpp b/Telegram/SourceFiles/calls/calls_call.cpp index 17eebdd4c..4b01808a1 100644 --- a/Telegram/SourceFiles/calls/calls_call.cpp +++ b/Telegram/SourceFiles/calls/calls_call.cpp @@ -63,16 +63,16 @@ void ConvertEndpoint(std::vector &ep, const MTPDphoneConnectio } constexpr auto kFingerprintDataSize = 256; -uint64 ComputeFingerprint(const std::array &authKey) { +uint64_t ComputeFingerprint(const std::array &authKey) { auto hash = openssl::Sha1(authKey); - return (gsl::to_integer(hash[19]) << 56) - | (gsl::to_integer(hash[18]) << 48) - | (gsl::to_integer(hash[17]) << 40) - | (gsl::to_integer(hash[16]) << 32) - | (gsl::to_integer(hash[15]) << 24) - | (gsl::to_integer(hash[14]) << 16) - | (gsl::to_integer(hash[13]) << 8) - | (gsl::to_integer(hash[12])); + return (gsl::to_integer(hash[19]) << 56) + | (gsl::to_integer(hash[18]) << 48) + | (gsl::to_integer(hash[17]) << 40) + | (gsl::to_integer(hash[16]) << 32) + | (gsl::to_integer(hash[15]) << 24) + | (gsl::to_integer(hash[14]) << 16) + | (gsl::to_integer(hash[13]) << 8) + | (gsl::to_integer(hash[12])); } } // namespace @@ -137,7 +137,7 @@ void Call::startOutgoing() { Expects(_type == Type::Outgoing); Expects(_state == State::Requesting); - request(MTPphone_RequestCall(_user->inputUser, MTP_int(rand_value()), MTP_bytes(_gaHash), MTP_phoneCallProtocol(MTP_flags(MTPDphoneCallProtocol::Flag::f_udp_p2p | MTPDphoneCallProtocol::Flag::f_udp_reflector), MTP_int(kMinLayer), MTP_int(kMaxLayer)))).done([this](const MTPphone_PhoneCall &result) { + request(MTPphone_RequestCall(_user->inputUser, MTP_int(rand_value()), MTP_bytes(_gaHash), MTP_phoneCallProtocol(MTP_flags(MTPDphoneCallProtocol::Flag::f_udp_p2p | MTPDphoneCallProtocol::Flag::f_udp_reflector), MTP_int(kMinLayer), MTP_int(kMaxLayer)))).done([this](const MTPphone_PhoneCall &result) { Expects(result.type() == mtpc_phone_phoneCall); setState(State::Waiting); @@ -267,7 +267,7 @@ void Call::startWaitingTrack() { _waitingTrack->playInLoop(); } -float64 Call::getWaitingSoundPeakValue() const { +double Call::getWaitingSoundPeakValue() const { if (_waitingTrack) { auto when = getms() + kSoundSampleMs / 4; return _waitingTrack->getPeakValue(when); diff --git a/Telegram/SourceFiles/calls/calls_call.h b/Telegram/SourceFiles/calls/calls_call.h index 447463b37..a014cfc57 100644 --- a/Telegram/SourceFiles/calls/calls_call.h +++ b/Telegram/SourceFiles/calls/calls_call.h @@ -38,8 +38,8 @@ class VoIPController; namespace Calls { struct DhConfig { - int32 version = 0; - int32 g = 0; + int32_t version = 0; + int32_t g = 0; std::vector p; }; @@ -115,7 +115,7 @@ public: } TimeMs getDurationMs() const; - float64 getWaitingSoundPeakValue() const; + double getWaitingSoundPeakValue() const; void answer(); void hangup(); @@ -179,9 +179,9 @@ private: MTP::AuthKey::Data _authKey; MTPPhoneCallProtocol _protocol; - uint64 _id = 0; - uint64 _accessHash = 0; - uint64 _keyFingerprint = 0; + uint64_t _id = 0; + uint64_t _accessHash = 0; + uint64_t _keyFingerprint = 0; std::unique_ptr _controller; diff --git a/Telegram/SourceFiles/calls/calls_emoji_fingerprint.cpp b/Telegram/SourceFiles/calls/calls_emoji_fingerprint.cpp index 334956654..10cacfbc7 100644 --- a/Telegram/SourceFiles/calls/calls_emoji_fingerprint.cpp +++ b/Telegram/SourceFiles/calls/calls_emoji_fingerprint.cpp @@ -112,16 +112,16 @@ ushort Offsets[] = { 620, 622, 624, 626, 628, 630, 632, 634, 636, 638, 640, 641, 642, 643, 644, 646, 648, 650, 652, 654, 656, 658 }; -uint64 ComputeEmojiIndex(base::const_byte_span bytes) { +uint64_t ComputeEmojiIndex(base::const_byte_span bytes) { Expects(bytes.size() == 8); - return ((gsl::to_integer(bytes[0]) & 0x7F) << 56) - | (gsl::to_integer(bytes[1]) << 48) - | (gsl::to_integer(bytes[2]) << 40) - | (gsl::to_integer(bytes[3]) << 32) - | (gsl::to_integer(bytes[4]) << 24) - | (gsl::to_integer(bytes[5]) << 16) - | (gsl::to_integer(bytes[6]) << 8) - | (gsl::to_integer(bytes[7])); + return ((gsl::to_integer(bytes[0]) & 0x7F) << 56) + | (gsl::to_integer(bytes[1]) << 48) + | (gsl::to_integer(bytes[2]) << 40) + | (gsl::to_integer(bytes[3]) << 32) + | (gsl::to_integer(bytes[4]) << 24) + | (gsl::to_integer(bytes[5]) << 16) + | (gsl::to_integer(bytes[6]) << 8) + | (gsl::to_integer(bytes[7])); } } // namespace diff --git a/Telegram/SourceFiles/calls/calls_panel.cpp b/Telegram/SourceFiles/calls/calls_panel.cpp index 2a7aa37a9..76cb8a422 100644 --- a/Telegram/SourceFiles/calls/calls_panel.cpp +++ b/Telegram/SourceFiles/calls/calls_panel.cpp @@ -49,8 +49,8 @@ class Panel::Button : public Ui::RippleButton { public: Button(QWidget *parent, const style::CallButton &stFrom, const style::CallButton *stTo = nullptr); - void setProgress(float64 progress); - void setOuterValue(float64 value); + void setProgress(double progress); + void setOuterValue(double value); protected: void paintEvent(QPaintEvent *e) override; @@ -66,13 +66,13 @@ private: not_null _stFrom; const style::CallButton *_stTo = nullptr; - float64 _progress = 0.; + double _progress = 0.; QImage _bgMask, _bg; QPixmap _bgFrom, _bgTo; QImage _iconMixedMask, _iconFrom, _iconTo, _iconMixed; - float64 _outerValue = 0.; + double _outerValue = 0.; Animation _outerAnimation; }; @@ -114,7 +114,7 @@ Panel::Button::Button(QWidget *parent, const style::CallButton &stFrom, const st } } -void Panel::Button::setOuterValue(float64 value) { +void Panel::Button::setOuterValue(double value) { if (_outerValue != value) { _outerAnimation.start([this] { if (_progress == 0. || _progress == 1.) { @@ -125,7 +125,7 @@ void Panel::Button::setOuterValue(float64 value) { } } -void Panel::Button::setProgress(float64 progress) { +void Panel::Button::setProgress(double progress) { _progress = progress; update(); } @@ -208,7 +208,7 @@ void Panel::Button::mixIconMasks() { Painter p(&_iconMixedMask); PainterHighQualityEnabler hq(p); - auto paintIconMask = [this, &p](const QImage &mask, float64 angle) { + auto paintIconMask = [this, &p](const QImage &mask, double angle) { auto skipFrom = _stFrom->button.rippleAreaSize / 2; p.translate(skipFrom, skipFrom); p.rotate(angle); diff --git a/Telegram/SourceFiles/chat_helpers/bot_keyboard.cpp b/Telegram/SourceFiles/chat_helpers/bot_keyboard.cpp index e933ba2b3..a1603aa1a 100644 --- a/Telegram/SourceFiles/chat_helpers/bot_keyboard.cpp +++ b/Telegram/SourceFiles/chat_helpers/bot_keyboard.cpp @@ -60,7 +60,7 @@ int BotKeyboard::Style::buttonRadius() const { return st::buttonRadius; } -void BotKeyboard::Style::paintButtonBg(Painter &p, const QRect &rect, float64 howMuchOver) const { +void BotKeyboard::Style::paintButtonBg(Painter &p, const QRect &rect, double howMuchOver) const { App::roundRect(p, rect, st::botKbBg, BotKeyboardCorners); } diff --git a/Telegram/SourceFiles/chat_helpers/bot_keyboard.h b/Telegram/SourceFiles/chat_helpers/bot_keyboard.h index a30731825..4ef072dd7 100644 --- a/Telegram/SourceFiles/chat_helpers/bot_keyboard.h +++ b/Telegram/SourceFiles/chat_helpers/bot_keyboard.h @@ -95,7 +95,7 @@ private: void repaint(not_null item) const override; protected: - void paintButtonBg(Painter &p, const QRect &rect, float64 howMuchOver) const override; + void paintButtonBg(Painter &p, const QRect &rect, double howMuchOver) const override; void paintButtonIcon(Painter &p, const QRect &rect, int outerWidth, HistoryMessageReplyMarkup::Button::Type type) const override; void paintButtonLoading(Painter &p, const QRect &rect) const override; int minButtonWidth(HistoryMessageReplyMarkup::Button::Type type) const override; diff --git a/Telegram/SourceFiles/chat_helpers/emoji_list_widget.cpp b/Telegram/SourceFiles/chat_helpers/emoji_list_widget.cpp index 1c41a9cb3..96397f6a7 100644 --- a/Telegram/SourceFiles/chat_helpers/emoji_list_widget.cpp +++ b/Telegram/SourceFiles/chat_helpers/emoji_list_widget.cpp @@ -186,7 +186,7 @@ void EmojiColorPicker::mouseReleaseEvent(QMouseEvent *e) { void EmojiColorPicker::handleMouseRelease(QPoint globalPos) { _lastMousePos = globalPos; - int32 pressed = _pressedSel; + int32_t pressed = _pressedSel; _pressedSel = -1; updateSelected(); @@ -492,7 +492,7 @@ void EmojiListWidget::mousePressEvent(QMouseEvent *e) { } void EmojiListWidget::mouseReleaseEvent(QMouseEvent *e) { - int32 pressed = _pressedSel; + int32_t pressed = _pressedSel; _pressedSel = -1; _lastMousePos = e->globalPos(); @@ -553,7 +553,7 @@ void EmojiListWidget::onShowPicker() { y += _picker->height() - st::buttonRadius + st::emojiPanSize.height() - st::buttonRadius; } auto xmax = width() - _picker->width(); - auto coef = float64(sel % kEmojiPanelPerRow) / float64(kEmojiPanelPerRow - 1); + auto coef = double(sel % kEmojiPanelPerRow) / double(kEmojiPanelPerRow - 1); if (rtl()) coef = 1. - coef; _picker->move(qRound(xmax * coef), y); diff --git a/Telegram/SourceFiles/chat_helpers/emoji_list_widget.h b/Telegram/SourceFiles/chat_helpers/emoji_list_widget.h index 42dcd7843..1d7f74327 100644 --- a/Telegram/SourceFiles/chat_helpers/emoji_list_widget.h +++ b/Telegram/SourceFiles/chat_helpers/emoji_list_widget.h @@ -155,7 +155,7 @@ private: int _counts[kEmojiSectionCount]; QVector _emoji[kEmojiSectionCount]; - int32 _esize; + int32_t _esize; int _selected = -1; int _pressedSel = -1; diff --git a/Telegram/SourceFiles/chat_helpers/field_autocomplete.cpp b/Telegram/SourceFiles/chat_helpers/field_autocomplete.cpp index f24cd52fa..6ef4c3c79 100644 --- a/Telegram/SourceFiles/chat_helpers/field_autocomplete.cpp +++ b/Telegram/SourceFiles/chat_helpers/field_autocomplete.cpp @@ -142,7 +142,7 @@ inline int indexOfInFirstN(const T &v, const U &elem, int last) { } void FieldAutocomplete::updateFiltered(bool resetScroll) { - int32 now = unixtime(), recentInlineBots = 0; + int32_t now = unixtime(), recentInlineBots = 0; internal::MentionRows mrows; internal::HashtagRows hrows; internal::BotCommandRows brows; @@ -190,7 +190,7 @@ void FieldAutocomplete::updateFiltered(bool resetScroll) { } } if (_chat) { - QMultiMap ordered; + QMultiMap ordered; mrows.reserve(mrows.size() + (_chat->participants.isEmpty() ? _chat->lastAuthors.size() : _chat->participants.size())); if (_chat->noParticipantInfo()) { Auth().api().requestFullPeer(_chat); @@ -219,7 +219,7 @@ void FieldAutocomplete::updateFiltered(bool resetScroll) { } } } else if (_channel && _channel->isMegagroup()) { - QMultiMap ordered; + QMultiMap ordered; if (_channel->mgInfo->lastParticipants.isEmpty() || _channel->lastParticipantsCountOutdated()) { Auth().api().requestLastParticipants(_channel); } else { @@ -246,7 +246,7 @@ void FieldAutocomplete::updateFiltered(bool resetScroll) { bool listAllSuggestions = _filter.isEmpty(); bool hasUsername = _filter.indexOf('@') > 0; QMap bots; - int32 cnt = 0; + int32_t cnt = 0; if (_chat) { if (_chat->noParticipantInfo()) { Auth().api().requestFullPeer(_chat); @@ -287,7 +287,7 @@ void FieldAutocomplete::updateFiltered(bool resetScroll) { } if (cnt) { brows.reserve(cnt); - int32 botStatus = _chat ? _chat->botStatus : ((_channel && _channel->isMegagroup()) ? _channel->mgInfo->botStatus : -1); + int32_t botStatus = _chat ? _chat->botStatus : ((_channel && _channel->isMegagroup()) ? _channel->mgInfo->botStatus : -1); if (_chat) { for (auto i = _chat->lastAuthors.cbegin(), e = _chat->lastAuthors.cend(); i != e; ++i) { auto user = *i; @@ -314,7 +314,7 @@ void FieldAutocomplete::updateFiltered(bool resetScroll) { if (!bots.isEmpty()) { for (QMap::const_iterator i = bots.cbegin(), e = bots.cend(); i != e; ++i) { UserData *user = i.key(); - for (int32 j = 0, l = user->botInfo->commands.size(); j < l; ++j) { + for (int32_t j = 0, l = user->botInfo->commands.size(); j < l; ++j) { if (!listAllSuggestions) { QString toFilter = (hasUsername || botStatus == 0 || botStatus == 2) ? user->botInfo->commands.at(j).command + '@' + user->username : user->botInfo->commands.at(j).command; if (!toFilter.startsWith(_filter, Qt::CaseInsensitive)/* || toFilter.size() == _filter.size()*/) continue; @@ -364,10 +364,10 @@ void FieldAutocomplete::setBoundings(QRect boundings) { } void FieldAutocomplete::recount(bool resetScroll) { - int32 h = 0, oldst = _scroll->scrollTop(), st = oldst, maxh = 4.5 * st::mentionHeight; + int32_t h = 0, oldst = _scroll->scrollTop(), st = oldst, maxh = 4.5 * st::mentionHeight; if (!_srows.isEmpty()) { - int32 stickersPerRow = qMax(1, int32(_boundings.width() - 2 * st::stickerPanPadding) / int32(st::stickerPanSize.width())); - int32 rows = rowscount(_srows.size(), stickersPerRow); + int32_t stickersPerRow = qMax(1, int32_t(_boundings.width() - 2 * st::stickerPanPadding) / int32_t(st::stickerPanSize.width())); + int32_t rows = rowscount(_srows.size(), stickersPerRow); h = st::stickerPanPadding + rows * st::stickerPanSize.height(); } else if (!_mrows.isEmpty()) { h = _mrows.size() * st::mentionHeight; @@ -465,11 +465,11 @@ UserData *FieldAutocomplete::user() const { return _user; } -int32 FieldAutocomplete::innerTop() { +int32_t FieldAutocomplete::innerTop() { return _scroll->scrollTop(); } -int32 FieldAutocomplete::innerBottom() { +int32_t FieldAutocomplete::innerBottom() { return _scroll->scrollTop() + _scroll->height(); } @@ -531,20 +531,20 @@ void FieldAutocompleteInner::paintEvent(QPaintEvent *e) { QRect r(e->rect()); if (r != rect()) p.setClipRect(r); - int32 atwidth = st::mentionFont->width('@'), hashwidth = st::mentionFont->width('#'); - int32 mentionleft = 2 * st::mentionPadding.left() + st::mentionPhotoSize; - int32 mentionwidth = width() - mentionleft - 2 * st::mentionPadding.right(); - int32 htagleft = st::historyAttach.width + st::historyComposeField.textMrg.left() - st::lineWidth, htagwidth = width() - st::mentionPadding.right() - htagleft - st::mentionScroll.width; + int32_t atwidth = st::mentionFont->width('@'), hashwidth = st::mentionFont->width('#'); + int32_t mentionleft = 2 * st::mentionPadding.left() + st::mentionPhotoSize; + int32_t mentionwidth = width() - mentionleft - 2 * st::mentionPadding.right(); + int32_t htagleft = st::historyAttach.width + st::historyComposeField.textMrg.left() - st::lineWidth, htagwidth = width() - st::mentionPadding.right() - htagleft - st::mentionScroll.width; if (!_srows->isEmpty()) { - int32 rows = rowscount(_srows->size(), _stickersPerRow); - int32 fromrow = floorclamp(r.y() - st::stickerPanPadding, st::stickerPanSize.height(), 0, rows); - int32 torow = ceilclamp(r.y() + r.height() - st::stickerPanPadding, st::stickerPanSize.height(), 0, rows); - int32 fromcol = floorclamp(r.x() - st::stickerPanPadding, st::stickerPanSize.width(), 0, _stickersPerRow); - int32 tocol = ceilclamp(r.x() + r.width() - st::stickerPanPadding, st::stickerPanSize.width(), 0, _stickersPerRow); - for (int32 row = fromrow; row < torow; ++row) { - for (int32 col = fromcol; col < tocol; ++col) { - int32 index = row * _stickersPerRow + col; + int32_t rows = rowscount(_srows->size(), _stickersPerRow); + int32_t fromrow = floorclamp(r.y() - st::stickerPanPadding, st::stickerPanSize.height(), 0, rows); + int32_t torow = ceilclamp(r.y() + r.height() - st::stickerPanPadding, st::stickerPanSize.height(), 0, rows); + int32_t fromcol = floorclamp(r.x() - st::stickerPanPadding, st::stickerPanSize.width(), 0, _stickersPerRow); + int32_t tocol = ceilclamp(r.x() + r.width() - st::stickerPanPadding, st::stickerPanSize.width(), 0, _stickersPerRow); + for (int32_t row = fromrow; row < torow; ++row) { + for (int32_t col = fromcol; col < tocol; ++col) { + int32_t index = row * _stickersPerRow + col; if (index >= _srows->size()) break; DocumentData *sticker = _srows->at(index); @@ -564,9 +564,9 @@ void FieldAutocompleteInner::paintEvent(QPaintEvent *e) { sticker->checkSticker(); } - float64 coef = qMin((st::stickerPanSize.width() - st::buttonRadius * 2) / float64(sticker->dimensions.width()), (st::stickerPanSize.height() - st::buttonRadius * 2) / float64(sticker->dimensions.height())); + double coef = qMin((st::stickerPanSize.width() - st::buttonRadius * 2) / double(sticker->dimensions.width()), (st::stickerPanSize.height() - st::buttonRadius * 2) / double(sticker->dimensions.height())); if (coef > 1) coef = 1; - int32 w = qRound(coef * sticker->dimensions.width()), h = qRound(coef * sticker->dimensions.height()); + int32_t w = qRound(coef * sticker->dimensions.width()), h = qRound(coef * sticker->dimensions.height()); if (w < 1) w = 1; if (h < 1) h = 1; QPoint ppos = pos + QPoint((st::stickerPanSize.width() - w) / 2, (st::stickerPanSize.height() - h) / 2); @@ -578,13 +578,13 @@ void FieldAutocompleteInner::paintEvent(QPaintEvent *e) { } } } else { - int32 from = qFloor(e->rect().top() / st::mentionHeight), to = qFloor(e->rect().bottom() / st::mentionHeight) + 1; - int32 last = _mrows->isEmpty() ? (_hrows->isEmpty() ? _brows->size() : _hrows->size()) : _mrows->size(); + int32_t from = qFloor(e->rect().top() / st::mentionHeight), to = qFloor(e->rect().bottom() / st::mentionHeight) + 1; + int32_t last = _mrows->isEmpty() ? (_hrows->isEmpty() ? _brows->size() : _hrows->size()) : _mrows->size(); auto filter = _parent->filter(); bool hasUsername = filter.indexOf('@') > 0; int filterSize = filter.size(); bool filterIsEmpty = filter.isEmpty(); - for (int32 i = from; i < to; ++i) { + for (int32_t i = from; i < to; ++i) { if (i >= last) break; bool selected = (i == _sel); @@ -599,7 +599,7 @@ void FieldAutocompleteInner::paintEvent(QPaintEvent *e) { UserData *user = _mrows->at(i); QString first = (!filterIsEmpty && user->username.startsWith(filter, Qt::CaseInsensitive)) ? ('@' + user->username.mid(0, filterSize)) : QString(); QString second = first.isEmpty() ? (user->username.isEmpty() ? QString() : ('@' + user->username)) : user->username.mid(filterSize); - int32 firstwidth = st::mentionFont->width(first), secondwidth = st::mentionFont->width(second), unamewidth = firstwidth + secondwidth, namewidth = user->nameText.maxWidth(); + int32_t firstwidth = st::mentionFont->width(first), secondwidth = st::mentionFont->width(second), unamewidth = firstwidth + secondwidth, namewidth = user->nameText.maxWidth(); if (mentionwidth < unamewidth + namewidth) { namewidth = (mentionwidth * namewidth) / (namewidth + unamewidth); unamewidth = mentionwidth - namewidth; @@ -631,7 +631,7 @@ void FieldAutocompleteInner::paintEvent(QPaintEvent *e) { QString hrow = _hrows->at(i); QString first = filterIsEmpty ? QString() : ('#' + hrow.mid(0, filterSize)); QString second = filterIsEmpty ? ('#' + hrow) : hrow.mid(filterSize); - int32 firstwidth = st::mentionFont->width(first), secondwidth = st::mentionFont->width(second); + int32_t firstwidth = st::mentionFont->width(first), secondwidth = st::mentionFont->width(second); if (htagwidth < firstwidth + secondwidth) { if (htagwidth < firstwidth + st::mentionFont->elidew) { first = st::mentionFont->elided(first + second, htagwidth); @@ -655,7 +655,7 @@ void FieldAutocompleteInner::paintEvent(QPaintEvent *e) { const BotCommand *command = _brows->at(i).second; QString toHighlight = command->command; - int32 botStatus = _parent->chat() ? _parent->chat()->botStatus : ((_parent->channel() && _parent->channel()->isMegagroup()) ? _parent->channel()->mgInfo->botStatus : -1); + int32_t botStatus = _parent->chat() ? _parent->chat()->botStatus : ((_parent->channel() && _parent->channel()->isMegagroup()) ? _parent->channel()->mgInfo->botStatus : -1); if (hasUsername || botStatus == 0 || botStatus == 2) { toHighlight += '@' + user->username; } @@ -684,7 +684,7 @@ void FieldAutocompleteInner::paintEvent(QPaintEvent *e) { } void FieldAutocompleteInner::resizeEvent(QResizeEvent *e) { - _stickersPerRow = qMax(1, int32(width() - 2 * st::stickerPanPadding) / int32(st::stickerPanSize.width())); + _stickersPerRow = qMax(1, int32_t(width() - 2 * st::stickerPanPadding) / int32_t(st::stickerPanSize.width())); } void FieldAutocompleteInner::mouseMoveEvent(QMouseEvent *e) { @@ -704,8 +704,8 @@ void FieldAutocompleteInner::clearSel(bool hidden) { bool FieldAutocompleteInner::moveSel(int key) { _mouseSel = false; - int32 maxSel = (_mrows->isEmpty() ? (_hrows->isEmpty() ? (_brows->isEmpty() ? _srows->size() : _brows->size()) : _hrows->size()) : _mrows->size()); - int32 direction = (key == Qt::Key_Up) ? -1 : (key == Qt::Key_Down ? 1 : 0); + int32_t maxSel = (_mrows->isEmpty() ? (_hrows->isEmpty() ? (_brows->isEmpty() ? _srows->size() : _brows->size()) : _hrows->size()) : _mrows->size()); + int32_t direction = (key == Qt::Key_Up) ? -1 : (key == Qt::Key_Down ? 1 : 0); if (!_srows->isEmpty()) { if (key == Qt::Key_Left) { direction = -1; @@ -749,7 +749,7 @@ bool FieldAutocompleteInner::chooseSelected(FieldAutocomplete::ChooseMethod meth if (_sel >= 0 && _sel < _brows->size()) { UserData *user = _brows->at(_sel).first; const BotCommand *command(_brows->at(_sel).second); - int32 botStatus = _parent->chat() ? _parent->chat()->botStatus : ((_parent->channel() && _parent->channel()->isMegagroup()) ? _parent->channel()->mgInfo->botStatus : -1); + int32_t botStatus = _parent->chat() ? _parent->chat()->botStatus : ((_parent->channel() && _parent->channel()->isMegagroup()) ? _parent->channel()->mgInfo->botStatus : -1); if (botStatus == 0 || botStatus == 2 || _parent->filter().indexOf('@') > 0) { emit botCommandChosen('/' + command->command + '@' + user->username, method); } else { @@ -761,7 +761,7 @@ bool FieldAutocompleteInner::chooseSelected(FieldAutocomplete::ChooseMethod meth return false; } -void FieldAutocompleteInner::setRecentInlineBotsInRows(int32 bots) { +void FieldAutocompleteInner::setRecentInlineBotsInRows(int32_t bots) { _recentInlineBotsInRows = bots; } @@ -787,7 +787,7 @@ void FieldAutocompleteInner::mousePressEvent(QMouseEvent *e) { } else { UserData *toRemove = _mrows->at(_sel); RecentInlineBots &recent(cRefRecentInlineBots()); - int32 index = recent.indexOf(toRemove); + int32_t index = recent.indexOf(toRemove); if (index >= 0) { recent.remove(index); removed = true; @@ -812,7 +812,7 @@ void FieldAutocompleteInner::mousePressEvent(QMouseEvent *e) { void FieldAutocompleteInner::mouseReleaseEvent(QMouseEvent *e) { _previewTimer.stop(); - int32 pressed = _down; + int32_t pressed = _down; _down = -1; _mousePos = mapToGlobal(e->pos()); @@ -847,7 +847,7 @@ void FieldAutocompleteInner::updateSelectedRow() { if (_srows->isEmpty()) { update(0, _sel * st::mentionHeight, width(), st::mentionHeight); } else { - int32 row = _sel / _stickersPerRow, col = _sel % _stickersPerRow; + int32_t row = _sel / _stickersPerRow, col = _sel % _stickersPerRow; update(st::stickerPanPadding + col * st::stickerPanSize.width(), st::stickerPanPadding + row * st::stickerPanSize.height(), st::stickerPanSize.width(), st::stickerPanSize.height()); } } @@ -862,7 +862,7 @@ void FieldAutocompleteInner::setSel(int sel, bool scroll) { if (_srows->isEmpty()) { emit mustScrollTo(_sel * st::mentionHeight, (_sel + 1) * st::mentionHeight); } else { - int32 row = _sel / _stickersPerRow; + int32_t row = _sel / _stickersPerRow; emit mustScrollTo(st::stickerPanPadding + row * st::stickerPanSize.height(), st::stickerPanPadding + (row + 1) * st::stickerPanSize.height()); } } @@ -874,18 +874,18 @@ void FieldAutocompleteInner::onUpdateSelected(bool force) { if (_down >= 0 && !_previewShown) return; - int32 sel = -1, maxSel = 0; + int32_t sel = -1, maxSel = 0; if (!_srows->isEmpty()) { - int32 rows = rowscount(_srows->size(), _stickersPerRow); - int32 row = (mouse.y() >= st::stickerPanPadding) ? ((mouse.y() - st::stickerPanPadding) / st::stickerPanSize.height()) : -1; - int32 col = (mouse.x() >= st::stickerPanPadding) ? ((mouse.x() - st::stickerPanPadding) / st::stickerPanSize.width()) : -1; + int32_t rows = rowscount(_srows->size(), _stickersPerRow); + int32_t row = (mouse.y() >= st::stickerPanPadding) ? ((mouse.y() - st::stickerPanPadding) / st::stickerPanSize.height()) : -1; + int32_t col = (mouse.x() >= st::stickerPanPadding) ? ((mouse.x() - st::stickerPanPadding) / st::stickerPanSize.width()) : -1; if (row >= 0 && col >= 0) { sel = row * _stickersPerRow + col; } maxSel = _srows->size(); _overDelete = false; } else { - sel = mouse.y() / int32(st::mentionHeight); + sel = mouse.y() / int32_t(st::mentionHeight); maxSel = _mrows->isEmpty() ? (_hrows->isEmpty() ? _brows->size() : _hrows->size()) : _mrows->size(); _overDelete = (!_hrows->isEmpty() || (!_mrows->isEmpty() && sel < _recentInlineBotsInRows)) ? (mouse.x() >= width() - st::mentionHeight) : false; } diff --git a/Telegram/SourceFiles/chat_helpers/field_autocomplete.h b/Telegram/SourceFiles/chat_helpers/field_autocomplete.h index 6db13b67e..a01865390 100644 --- a/Telegram/SourceFiles/chat_helpers/field_autocomplete.h +++ b/Telegram/SourceFiles/chat_helpers/field_autocomplete.h @@ -52,8 +52,8 @@ public: ChannelData *channel() const; UserData *user() const; - int32 innerTop(); - int32 innerBottom(); + int32_t innerTop(); + int32_t innerBottom(); bool eventFilter(QObject *obj, QEvent *e) override; @@ -126,7 +126,7 @@ private: QRect _boundings; bool _addInlineBots; - int32 _width, _height; + int32_t _width, _height; bool _hiding = false; Animation _a_opacity; @@ -147,7 +147,7 @@ public: bool moveSel(int key); bool chooseSelected(FieldAutocomplete::ChooseMethod method) const; - void setRecentInlineBotsInRows(int32 bots); + void setRecentInlineBotsInRows(int32_t bots); signals: void mentionChosen(UserData *user, FieldAutocomplete::ChooseMethod method) const; @@ -180,8 +180,8 @@ private: HashtagRows *_hrows; BotCommandRows *_brows; StickerPack *_srows; - int32 _stickersPerRow, _recentInlineBotsInRows; - int32 _sel, _down; + int32_t _stickersPerRow, _recentInlineBotsInRows; + int32_t _sel, _down; bool _mouseSel; QPoint _mousePos; diff --git a/Telegram/SourceFiles/chat_helpers/gifs_list_widget.cpp b/Telegram/SourceFiles/chat_helpers/gifs_list_widget.cpp index 64a5bc9d4..7809f20ba 100644 --- a/Telegram/SourceFiles/chat_helpers/gifs_list_widget.cpp +++ b/Telegram/SourceFiles/chat_helpers/gifs_list_widget.cpp @@ -418,7 +418,7 @@ void GifsListWidget::processPanelHideFinished() { } } -bool GifsListWidget::inlineRowsAddItem(DocumentData *savedGif, InlineResult *result, Row &row, int32 &sumWidth) { +bool GifsListWidget::inlineRowsAddItem(DocumentData *savedGif, InlineResult *result, Row &row, int32_t &sumWidth) { LayoutItem *layout = nullptr; if (savedGif) { layout = layoutPrepareSavedGif(savedGif, (_rows.size() * MatrixRowShift) + row.items.size()); @@ -441,7 +441,7 @@ bool GifsListWidget::inlineRowsAddItem(DocumentData *savedGif, InlineResult *res return true; } -bool GifsListWidget::inlineRowFinalize(Row &row, int32 &sumWidth, bool force) { +bool GifsListWidget::inlineRowFinalize(Row &row, int32_t &sumWidth, bool force) { if (row.items.isEmpty()) return false; auto full = (row.items.size() >= kInlineItemsMaxPerRow); @@ -502,7 +502,7 @@ void GifsListWidget::clearInlineRows(bool resultsDeleted) { _rows.clear(); } -GifsListWidget::LayoutItem *GifsListWidget::layoutPrepareSavedGif(DocumentData *doc, int32 position) { +GifsListWidget::LayoutItem *GifsListWidget::layoutPrepareSavedGif(DocumentData *doc, int32_t position) { auto it = _gifLayouts.find(doc); if (it == _gifLayouts.cend()) { if (auto layout = LayoutItem::createLayoutGif(this, doc)) { @@ -518,7 +518,7 @@ GifsListWidget::LayoutItem *GifsListWidget::layoutPrepareSavedGif(DocumentData * return it->second.get(); } -GifsListWidget::LayoutItem *GifsListWidget::layoutPrepareInlineResult(InlineResult *result, int32 position) { +GifsListWidget::LayoutItem *GifsListWidget::layoutPrepareInlineResult(InlineResult *result, int32_t position) { auto it = _inlineLayouts.find(result); if (it == _inlineLayouts.cend()) { if (auto layout = LayoutItem::createLayout(this, result, _inlineWithThumb)) { @@ -562,7 +562,7 @@ void GifsListWidget::deleteUnusedInlineLayouts() { } } -GifsListWidget::Row &GifsListWidget::layoutInlineRow(Row &row, int32 sumWidth) { +GifsListWidget::Row &GifsListWidget::layoutInlineRow(Row &row, int32_t sumWidth) { auto count = int(row.items.size()); Assert(count <= kInlineItemsMaxPerRow); @@ -640,7 +640,7 @@ int GifsListWidget::refreshInlineRows(const InlineCacheEntry *entry, bool result inlineRowFinalize(row, sumWidth, true); } - int32 h = countHeight(); + int32_t h = countHeight(); if (h != height()) resize(width(), h); update(); @@ -763,7 +763,7 @@ void GifsListWidget::beforeHiding() { } } -bool GifsListWidget::refreshInlineRows(int32 *added) { +bool GifsListWidget::refreshInlineRows(int32_t *added) { auto it = _inlineCache.find(_inlineQuery); const InlineCacheEntry *entry = nullptr; if (it != _inlineCache.cend()) { @@ -775,7 +775,7 @@ bool GifsListWidget::refreshInlineRows(int32 *added) { return (entry != nullptr); } -int32 GifsListWidget::showInlineRows(bool newResults) { +int32_t GifsListWidget::showInlineRows(bool newResults) { auto added = 0; auto clear = !refreshInlineRows(&added); if (newResults) { diff --git a/Telegram/SourceFiles/chat_helpers/gifs_list_widget.h b/Telegram/SourceFiles/chat_helpers/gifs_list_widget.h index 6dfa4b3d8..a7321275d 100644 --- a/Telegram/SourceFiles/chat_helpers/gifs_list_widget.h +++ b/Telegram/SourceFiles/chat_helpers/gifs_list_widget.h @@ -117,8 +117,8 @@ private: int refreshInlineRows(const InlineCacheEntry *results, bool resultsDeleted); void checkLoadMore(); - int32 showInlineRows(bool newResults); - bool refreshInlineRows(int32 *added = 0); + int32_t showInlineRows(bool newResults); + bool refreshInlineRows(int32_t *added = 0); void inlineResultsDone(const MTPmessages_BotResults &result); void updateSelected(); @@ -137,15 +137,15 @@ private: void clearInlineRows(bool resultsDeleted); std::map> _gifLayouts; - LayoutItem *layoutPrepareSavedGif(DocumentData *doc, int32 position); + LayoutItem *layoutPrepareSavedGif(DocumentData *doc, int32_t position); std::map> _inlineLayouts; - LayoutItem *layoutPrepareInlineResult(InlineResult *result, int32 position); + LayoutItem *layoutPrepareInlineResult(InlineResult *result, int32_t position); - bool inlineRowsAddItem(DocumentData *savedGif, InlineResult *result, Row &row, int32 &sumWidth); - bool inlineRowFinalize(Row &row, int32 &sumWidth, bool force = false); + bool inlineRowsAddItem(DocumentData *savedGif, InlineResult *result, Row &row, int32_t &sumWidth); + bool inlineRowFinalize(Row &row, int32_t &sumWidth, bool force = false); - Row &layoutInlineRow(Row &row, int32 sumWidth = 0); + Row &layoutInlineRow(Row &row, int32_t sumWidth = 0); void deleteUnusedGifLayouts(); void deleteUnusedInlineLayouts(); diff --git a/Telegram/SourceFiles/chat_helpers/message_field.cpp b/Telegram/SourceFiles/chat_helpers/message_field.cpp index 5a03876d6..54302e64c 100644 --- a/Telegram/SourceFiles/chat_helpers/message_field.cpp +++ b/Telegram/SourceFiles/chat_helpers/message_field.cpp @@ -144,8 +144,8 @@ void MessageField::dropEvent(QDropEvent *e) { bool MessageField::canInsertFromMimeData(const QMimeData *source) const { if (source->hasUrls()) { - int32 files = 0; - for (int32 i = 0; i < source->urls().size(); ++i) { + int32_t files = 0; + for (int32_t i = 0; i < source->urls().size(); ++i) { if (source->urls().at(i).isLocalFile()) { ++files; } diff --git a/Telegram/SourceFiles/chat_helpers/stickers.cpp b/Telegram/SourceFiles/chat_helpers/stickers.cpp index 2342103c2..27f6d81f0 100644 --- a/Telegram/SourceFiles/chat_helpers/stickers.cpp +++ b/Telegram/SourceFiles/chat_helpers/stickers.cpp @@ -43,7 +43,7 @@ void ApplyArchivedResult(const MTPDmessages_stickerSetInstallResultArchive &d) { auto &order = Global::RefStickerSetsOrder(); Order archived; archived.reserve(v.size()); - QMap setsToRequest; + QMap setsToRequest; for_const (auto &stickerSet, v) { const MTPDstickerSet *setData = nullptr; switch (stickerSet.type()) { @@ -96,7 +96,7 @@ bool ApplyArchivedResultFake() { auto sets = QVector(); for (auto &set : Global::RefStickerSets()) { if ((set.flags & MTPDstickerSet::Flag::f_installed) && !(set.flags & MTPDstickerSet_ClientFlag::f_special)) { - if (rand_value() % 128 < 64) { + if (rand_value() % 128 < 64) { auto data = MTP_stickerSet(MTP_flags(set.flags | MTPDstickerSet::Flag::f_archived), MTP_long(set.id), MTP_long(set.access), MTP_string(set.title), MTP_string(set.shortName), MTP_int(set.count), MTP_int(set.hash)); sets.push_back(MTP_stickerSetCovered(data, MTP_documentEmpty(MTP_long(0)))); } @@ -108,7 +108,7 @@ bool ApplyArchivedResultFake() { return true; } -void InstallLocally(uint64 setId) { +void InstallLocally(uint64_t setId) { auto &sets = Global::RefStickerSets(); auto it = sets.find(setId); if (it == sets.end()) { @@ -151,7 +151,7 @@ void InstallLocally(uint64 setId) { Auth().data().stickersUpdated().notify(true); } -void UndoInstallLocally(uint64 setId) { +void UndoInstallLocally(uint64_t setId) { auto &sets = Global::RefStickerSets(); auto it = sets.find(setId); if (it == sets.end()) { @@ -172,7 +172,7 @@ void UndoInstallLocally(uint64 setId) { Ui::show(Box(lang(lng_stickers_not_found)), KeepOtherLayers); } -void MarkFeaturedAsRead(uint64 setId) { +void MarkFeaturedAsRead(uint64_t setId) { if (!FeaturedReaderInstance) { if (auto main = App::main()) { FeaturedReaderInstance = object_ptr(main); @@ -338,12 +338,12 @@ void SetFaved(not_null document, bool faved) { } } -void SetsReceived(const QVector &data, int32 hash) { +void SetsReceived(const QVector &data, int32_t hash) { auto &setsOrder = Global::RefStickerSetsOrder(); setsOrder.clear(); auto &sets = Global::RefStickerSets(); - QMap setsToRequest; + QMap setsToRequest; for (auto &set : sets) { if (!(set.flags & MTPDstickerSet::Flag::f_archived)) { set.flags &= ~MTPDstickerSet::Flag::f_installed; // mark for removing @@ -425,7 +425,7 @@ void SetPackAndEmoji(Set &set, StickerPack &&pack, const QVector } } -void SpecialSetReceived(uint64 setId, const QString &setTitle, const QVector &items, int32 hash, const QVector &packs) { +void SpecialSetReceived(uint64_t setId, const QString &setTitle, const QVector &items, int32_t hash, const QVector &packs) { auto &sets = Global::RefStickerSets(); auto it = sets.find(setId); @@ -503,8 +503,8 @@ void SpecialSetReceived(uint64 setId, const QString &setTitle, const QVector &data, const QVector &unread, int32 hash) { - OrderedSet unreadMap; +void FeaturedSetsReceived(const QVector &data, const QVector &unread, int32_t hash) { + OrderedSet unreadMap; for_const (auto &unreadSetId, unread) { unreadMap.insert(unreadSetId.v); } @@ -513,7 +513,7 @@ void FeaturedSetsReceived(const QVector &data, const QVect setsOrder.clear(); auto &sets = Global::RefStickerSets(); - QMap setsToRequest; + QMap setsToRequest; for (auto &set : sets) { set.flags &= ~MTPDstickerSet_ClientFlag::f_featured; // mark for removing } @@ -606,7 +606,7 @@ void FeaturedSetsReceived(const QVector &data, const QVect Auth().data().stickersUpdated().notify(true); } -void GifsReceived(const QVector &items, int32 hash) { +void GifsReceived(const QVector &items, int32_t hash) { auto &saved = cRefSavedGifs(); saved.clear(); @@ -632,7 +632,7 @@ void GifsReceived(const QVector &items, int32 hash) { StickerPack GetListByEmoji(not_null emoji) { auto original = emoji->original(); auto result = StickerPack(); - auto setsToRequest = QMap(); + auto setsToRequest = QMap(); auto &sets = Global::RefStickerSets(); auto faved = StickerPack(); @@ -840,7 +840,7 @@ FeaturedReader::FeaturedReader(QObject *parent) : QObject(parent) _timer->setTimeoutHandler([this] { readSets(); }); } -void FeaturedReader::scheduleRead(uint64 setId) { +void FeaturedReader::scheduleRead(uint64_t setId) { if (!_setIds.contains(setId)) { _setIds.insert(setId); _timer->start(kReadFeaturedSetsTimeoutMs); diff --git a/Telegram/SourceFiles/chat_helpers/stickers.h b/Telegram/SourceFiles/chat_helpers/stickers.h index 4d9b737c0..7b101bf7a 100644 --- a/Telegram/SourceFiles/chat_helpers/stickers.h +++ b/Telegram/SourceFiles/chat_helpers/stickers.h @@ -28,16 +28,16 @@ constexpr auto kPanelPerRow = 5; void ApplyArchivedResult(const MTPDmessages_stickerSetInstallResultArchive &d); bool ApplyArchivedResultFake(); // For testing. -void InstallLocally(uint64 setId); -void UndoInstallLocally(uint64 setId); -void MarkFeaturedAsRead(uint64 setId); +void InstallLocally(uint64_t setId); +void UndoInstallLocally(uint64_t setId); +void MarkFeaturedAsRead(uint64_t setId); bool IsFaved(not_null document); void SetFaved(not_null document, bool faved); -void SetsReceived(const QVector &data, int32 hash); -void SpecialSetReceived(uint64 setId, const QString &setTitle, const QVector &items, int32 hash, const QVector &packs = QVector()); -void FeaturedSetsReceived(const QVector &data, const QVector &unread, int32 hash); -void GifsReceived(const QVector &items, int32 hash); +void SetsReceived(const QVector &data, int32_t hash); +void SpecialSetReceived(uint64_t setId, const QString &setTitle, const QVector &items, int32_t hash, const QVector &packs = QVector()); +void FeaturedSetsReceived(const QVector &data, const QVector &unread, int32_t hash); +void GifsReceived(const QVector &items, int32_t hash); StickerPack GetListByEmoji(not_null emoji); base::optional>> GetEmojiListFromSet( @@ -53,13 +53,13 @@ namespace internal { class FeaturedReader : public QObject, private MTP::Sender { public: FeaturedReader(QObject *parent); - void scheduleRead(uint64 setId); + void scheduleRead(uint64_t setId); private: void readSets(); object_ptr _timer; - OrderedSet _setIds; + OrderedSet _setIds; }; diff --git a/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp b/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp index b18d8517f..259fb9333 100644 --- a/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp +++ b/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp @@ -46,11 +46,11 @@ constexpr auto kInlineItemsMaxPerRow = 5; } // namespace struct StickerIcon { - StickerIcon(uint64 setId) : setId(setId) { + StickerIcon(uint64_t setId) : setId(setId) { } - StickerIcon(uint64 setId, DocumentData *sticker, int32 pixw, int32 pixh) : setId(setId), sticker(sticker), pixw(pixw), pixh(pixh) { + StickerIcon(uint64_t setId, DocumentData *sticker, int32_t pixw, int32_t pixh) : setId(setId), sticker(sticker), pixw(pixw), pixh(pixh) { } - uint64 setId = 0; + uint64_t setId = 0; DocumentData *sticker = nullptr; ChannelData *megagroup = nullptr; int pixw = 0; @@ -63,7 +63,7 @@ public: Footer(not_null parent); void preloadImages(); - void validateSelectedIcon(uint64 setId, ValidateIconAnimations animations); + void validateSelectedIcon(uint64_t setId, ValidateIconAnimations animations); void refreshIcons(ValidateIconAnimations animations); bool hasOnlyFeaturedSets() const; @@ -143,7 +143,7 @@ void StickersListWidget::Footer::preloadImages() { }); } -void StickersListWidget::Footer::validateSelectedIcon(uint64 setId, ValidateIconAnimations animations) { +void StickersListWidget::Footer::validateSelectedIcon(uint64_t setId, ValidateIconAnimations animations) { auto newSel = 0; for (auto i = 0, l = _icons.size(); i != l; ++i) { if (_icons[i].setId == setId) { @@ -214,7 +214,7 @@ void StickersListWidget::Footer::paintEvent(QPaintEvent *e) { } else if (icon.megagroup) { icon.megagroup->paintUserpicLeft(p, x + (st::emojiCategory.width - st::stickerGroupCategorySize) / 2, _iconsTop + (st::emojiCategory.height - st::stickerGroupCategorySize) / 2, width(), st::stickerGroupCategorySize); } else { - auto getSpecialSetIcon = [](uint64 setId) { + auto getSpecialSetIcon = [](uint64_t setId) { if (setId == Stickers::FeaturedSetId) { return &st::stickersTrending; } else if (setId == Stickers::FavedSetId) { @@ -344,7 +344,7 @@ void StickersListWidget::Footer::updateSelected() { } auto p = mapFromGlobal(_iconsMousePos); - int32 x = p.x(), y = p.y(), newOver = -1; + int32_t x = p.x(), y = p.y(), newOver = -1; if (rtl()) x = width() - x; x -= _iconsLeft; if (x >= st::emojiCategory.width * (kVisibleIconsCount - 1) && x < st::emojiCategory.width * kVisibleIconsCount && y >= _iconsTop && y < _iconsTop + st::emojiCategory.height) { @@ -416,7 +416,7 @@ void StickersListWidget::validateSelectedIcon(ValidateIconAnimations animations) void StickersListWidget::Footer::step_icons(TimeMs ms, bool timer) { if (_iconsStartAnim) { - auto dt = (ms - _iconsStartAnim) / float64(st::stickerIconMove); + auto dt = (ms - _iconsStartAnim) / double(st::stickerIconMove); if (dt >= 1) { _iconsStartAnim = 0; _iconsX.finish(); @@ -575,11 +575,11 @@ int StickersListWidget::countHeight() { return qMax(minimalLastHeight, countResult()) + st::stickerPanPadding; } -void StickersListWidget::installedLocally(uint64 setId) { +void StickersListWidget::installedLocally(uint64_t setId) { _installedLocallySets.insert(setId); } -void StickersListWidget::notInstalledLocally(uint64 setId) { +void StickersListWidget::notInstalledLocally(uint64_t setId) { _installedLocallySets.remove(setId); } @@ -827,7 +827,7 @@ void StickersListWidget::paintSticker(Painter &p, Set &set, int y, int index, bo sticker->checkSticker(); } - auto coef = qMin((st::stickerPanSize.width() - st::buttonRadius * 2) / float64(sticker->dimensions.width()), (st::stickerPanSize.height() - st::buttonRadius * 2) / float64(sticker->dimensions.height())); + auto coef = qMin((st::stickerPanSize.width() - st::buttonRadius * 2) / double(sticker->dimensions.width()), (st::stickerPanSize.height() - st::buttonRadius * 2) / double(sticker->dimensions.height())); if (coef > 1) coef = 1; auto w = qMax(qRound(coef * sticker->dimensions.width()), 1); auto h = qMax(qRound(coef * sticker->dimensions.height()), 1); @@ -1041,7 +1041,7 @@ void StickersListWidget::removeRecentSticker(int section, int index) { bool refresh = false; auto sticker = _mySets[section].pack[index]; auto &recent = cGetRecentStickers(); - for (int32 i = 0, l = recent.size(); i < l; ++i) { + for (int32_t i = 0, l = recent.size(); i < l; ++i) { if (recent.at(i).first == sticker) { recent.removeAt(i); Local::writeUserSettings(); @@ -1198,14 +1198,14 @@ void StickersListWidget::preloadImages() { } } -uint64 StickersListWidget::currentSet(int yOffset) const { +uint64_t StickersListWidget::currentSet(int yOffset) const { if (_section == Section::Featured) { return Stickers::FeaturedSetId; } return _mySets.isEmpty() ? Stickers::RecentSetId : _mySets[sectionInfoByOffset(yOffset).section].id; } -void StickersListWidget::appendSet(Sets &to, uint64 setId, AppendSkip skip) { +void StickersListWidget::appendSet(Sets &to, uint64_t setId, AppendSkip skip) { auto &sets = Global::StickerSets(); auto it = sets.constFind(setId); if (it == sets.cend() || it->stickers.isEmpty()) return; @@ -1281,7 +1281,7 @@ void StickersListWidget::refreshRecentStickers(bool performResize) { } if (performResize && (_section == Section::Stickers || _section == Section::Featured)) { - int32 h = countHeight(); + int32_t h = countHeight(); if (h != height()) { resize(width(), h); update(); @@ -1545,7 +1545,7 @@ void StickersListWidget::onPreview() { } } -void StickersListWidget::showStickerSet(uint64 setId) { +void StickersListWidget::showStickerSet(uint64_t setId) { clearSelection(); if (setId == Stickers::FeaturedSetId) { @@ -1615,7 +1615,7 @@ void StickersListWidget::showMegagroupSet(ChannelData *megagroup) { } } -void StickersListWidget::displaySet(uint64 setId) { +void StickersListWidget::displaySet(uint64_t setId) { if (setId == Stickers::MegagroupSetId) { if (_megagroupSet->canEditStickers()) { _displayingSetId = setId; @@ -1643,7 +1643,7 @@ void StickersListWidget::displaySet(uint64 setId) { } } -void StickersListWidget::installSet(uint64 setId) { +void StickersListWidget::installSet(uint64_t setId) { auto &sets = Global::StickerSets(); auto it = sets.constFind(setId); if (it != sets.cend()) { @@ -1683,7 +1683,7 @@ void StickersListWidget::removeMegagroupSet(bool locally) { }))); } -void StickersListWidget::removeSet(uint64 setId) { +void StickersListWidget::removeSet(uint64_t setId) { auto &sets = Global::StickerSets(); auto it = sets.constFind(setId); if (it != sets.cend()) { diff --git a/Telegram/SourceFiles/chat_helpers/stickers_list_widget.h b/Telegram/SourceFiles/chat_helpers/stickers_list_widget.h index 2359bd068..515db7ff5 100644 --- a/Telegram/SourceFiles/chat_helpers/stickers_list_widget.h +++ b/Telegram/SourceFiles/chat_helpers/stickers_list_widget.h @@ -46,7 +46,7 @@ public: void clearSelection() override; object_ptr createFooter() override; - void showStickerSet(uint64 setId); + void showStickerSet(uint64_t setId); void showMegagroupSet(ChannelData *megagroup); void refreshStickers(); @@ -56,10 +56,10 @@ public: void setVisibleTopBottom(int visibleTop, int visibleBottom) override; - uint64 currentSet(int yOffset) const; + uint64_t currentSet(int yOffset) const; - void installedLocally(uint64 setId); - void notInstalledLocally(uint64 setId); + void installedLocally(uint64_t setId); + void notInstalledLocally(uint64_t setId); void clearInstalledLocally(); ~StickersListWidget(); @@ -133,9 +133,9 @@ private: }; struct Set { - Set(uint64 id, MTPDstickerSet::Flags flags, const QString &title, int32 hoversSize, const StickerPack &pack = StickerPack()) : id(id), flags(flags), title(title), pack(pack) { + Set(uint64_t id, MTPDstickerSet::Flags flags, const QString &title, int32_t hoversSize, const StickerPack &pack = StickerPack()) : id(id), flags(flags), title(title), pack(pack) { } - uint64 id; + uint64_t id; MTPDstickerSet::Flags flags; QString title; StickerPack pack; @@ -148,10 +148,10 @@ private: SectionInfo sectionInfo(int section) const; SectionInfo sectionInfoByOffset(int yOffset) const; - void displaySet(uint64 setId); - void installSet(uint64 setId); + void displaySet(uint64_t setId); + void installSet(uint64_t setId); void removeMegagroupSet(bool locally); - void removeSet(uint64 setId); + void removeSet(uint64_t setId); bool setHasTitle(const Set &set) const; bool stickerHasDeleteButton(const Set &set, int index) const; @@ -204,7 +204,7 @@ private: Archived, Installed, }; - void appendSet(Sets &to, uint64 setId, AppendSkip skip = AppendSkip::None); + void appendSet(Sets &to, uint64_t setId, AppendSkip skip = AppendSkip::None); void selectEmoji(EmojiPtr emoji); int stickersLeft() const; @@ -216,14 +216,14 @@ private: ChannelData *_megagroupSet = nullptr; Sets _mySets; Sets _featuredSets; - OrderedSet _installedLocallySets; + OrderedSet _installedLocallySets; QList _custom; base::flat_set> _favedStickersMap; Section _section = Section::Stickers; - uint64 _displayingSetId = 0; - uint64 _removingSetId = 0; + uint64_t _displayingSetId = 0; + uint64_t _removingSetId = 0; Footer *_footer = nullptr; diff --git a/Telegram/SourceFiles/chat_helpers/tabbed_panel.cpp b/Telegram/SourceFiles/chat_helpers/tabbed_panel.cpp index 128531b2d..a0e96992b 100644 --- a/Telegram/SourceFiles/chat_helpers/tabbed_panel.cpp +++ b/Telegram/SourceFiles/chat_helpers/tabbed_panel.cpp @@ -376,7 +376,7 @@ bool TabbedPanel::eventFilter(QObject *obj, QEvent *e) { return false; } -void TabbedPanel::stickersInstalled(uint64 setId) { +void TabbedPanel::stickersInstalled(uint64_t setId) { if (isDestroying()) { return; } diff --git a/Telegram/SourceFiles/chat_helpers/tabbed_panel.h b/Telegram/SourceFiles/chat_helpers/tabbed_panel.h index 32438d302..ff82c5e8b 100644 --- a/Telegram/SourceFiles/chat_helpers/tabbed_panel.h +++ b/Telegram/SourceFiles/chat_helpers/tabbed_panel.h @@ -51,7 +51,7 @@ public: return _hiding || _hideTimer.isActive(); } - void stickersInstalled(uint64 setId); + void stickersInstalled(uint64_t setId); bool overlaps(const QRect &globalRect) const; diff --git a/Telegram/SourceFiles/chat_helpers/tabbed_section.cpp b/Telegram/SourceFiles/chat_helpers/tabbed_section.cpp index 5826c1ab2..d4ed01f60 100644 --- a/Telegram/SourceFiles/chat_helpers/tabbed_section.cpp +++ b/Telegram/SourceFiles/chat_helpers/tabbed_section.cpp @@ -69,7 +69,7 @@ QPointer TabbedSection::getSelector() const { return _selector.data(); } -void TabbedSection::stickersInstalled(uint64 setId) { +void TabbedSection::stickersInstalled(uint64_t setId) { _selector->stickersInstalled(setId); } diff --git a/Telegram/SourceFiles/chat_helpers/tabbed_section.h b/Telegram/SourceFiles/chat_helpers/tabbed_section.h index b155fe88b..ce30d0acb 100644 --- a/Telegram/SourceFiles/chat_helpers/tabbed_section.h +++ b/Telegram/SourceFiles/chat_helpers/tabbed_section.h @@ -40,7 +40,7 @@ public: object_ptr takeSelector(); QPointer getSelector() const; - void stickersInstalled(uint64 setId); + void stickersInstalled(uint64_t setId); // Float player interface. bool wheelEventFromFloatPlayer(QEvent *e, Window::Column myColumn, Window::Column playerColumn) override; diff --git a/Telegram/SourceFiles/chat_helpers/tabbed_selector.cpp b/Telegram/SourceFiles/chat_helpers/tabbed_selector.cpp index 9f7e7158c..67e1a21e5 100644 --- a/Telegram/SourceFiles/chat_helpers/tabbed_selector.cpp +++ b/Telegram/SourceFiles/chat_helpers/tabbed_selector.cpp @@ -52,7 +52,7 @@ public: void setFinalImages(Direction direction, QImage &&left, QImage &&right, QRect inner, bool wasSectionIcons); void start(); - void paintFrame(QPainter &p, float64 dt, float64 opacity); + void paintFrame(QPainter &p, double dt, double opacity); private: Direction _direction = Direction::LeftToRight; @@ -133,7 +133,7 @@ void TabbedSelector::SlideAnimation::start() { _frameIntsPerLineAdd = (_width - _innerWidth) + _frameIntsPerLineAdded; } -void TabbedSelector::SlideAnimation::paintFrame(QPainter &p, float64 dt, float64 opacity) { +void TabbedSelector::SlideAnimation::paintFrame(QPainter &p, double dt, double opacity) { Expects(started()); Expects(dt >= 0.); @@ -219,15 +219,15 @@ void TabbedSelector::SlideAnimation::paintFrame(QPainter &p, float64 dt, float64 if (opacity == 1.) { // Fill above the frame top with transparent. auto fillTopInts = (_frameInts + outerTop * _frameIntsPerLine + outerLeft); - auto fillWidth = (outerRight - outerLeft) * sizeof(uint32); + auto fillWidth = (outerRight - outerLeft) * sizeof(uint32_t); for (auto fillTop = _innerTop - outerTop; fillTop != 0; --fillTop) { memset(fillTopInts, 0, fillWidth); fillTopInts += _frameIntsPerLine; } // Fill to the left and to the right of the frame with transparent. - auto fillLeft = (_innerLeft - outerLeft) * sizeof(uint32); - auto fillRight = (outerRight - _innerRight) * sizeof(uint32); + auto fillLeft = (_innerLeft - outerLeft) * sizeof(uint32_t); + auto fillRight = (outerRight - _innerRight) * sizeof(uint32_t); if (fillLeft || fillRight) { auto fillInts = _frameInts + _innerTop * _frameIntsPerLine; for (auto y = _innerTop; y != _innerBottom; ++y) { @@ -250,7 +250,7 @@ void TabbedSelector::SlideAnimation::paintFrame(QPainter &p, float64 dt, float64 // Debug //frameInts = _frameInts; - //auto pattern = anim::shifted((static_cast(0xFF) << 24) | (static_cast(0xFF) << 16) | (static_cast(0xFF) << 8) | static_cast(0xFF)); + //auto pattern = anim::shifted((static_cast(0xFF) << 24) | (static_cast(0xFF) << 16) | (static_cast(0xFF) << 8) | static_cast(0xFF)); //for (auto y = 0; y != _finalHeight; ++y) { // for (auto x = 0; x != _finalWidth; ++x) { // auto source = *frameInts; @@ -514,7 +514,7 @@ void TabbedSelector::afterShown() { } } -void TabbedSelector::stickersInstalled(uint64 setId) { +void TabbedSelector::stickersInstalled(uint64_t setId) { _tabsSlider->setActiveSection(static_cast(SelectorTab::Stickers)); stickers()->showStickerSet(setId); } diff --git a/Telegram/SourceFiles/chat_helpers/tabbed_selector.h b/Telegram/SourceFiles/chat_helpers/tabbed_selector.h index b03d6d2f4..eb59f8714 100644 --- a/Telegram/SourceFiles/chat_helpers/tabbed_selector.h +++ b/Telegram/SourceFiles/chat_helpers/tabbed_selector.h @@ -60,7 +60,7 @@ public: void setRoundRadius(int radius); void refreshStickers(); - void stickersInstalled(uint64 setId); + void stickersInstalled(uint64_t setId); void showMegagroupSet(ChannelData *megagroup); void setCurrentPeer(PeerData *peer); diff --git a/Telegram/SourceFiles/codegen/CMakeLists.txt b/Telegram/SourceFiles/codegen/CMakeLists.txt new file mode 100644 index 000000000..1ccbdfb13 --- /dev/null +++ b/Telegram/SourceFiles/codegen/CMakeLists.txt @@ -0,0 +1,5 @@ +add_subdirectory(common) +add_subdirectory(emoji) +add_subdirectory(lang) +add_subdirectory(numbers) +add_subdirectory(style) diff --git a/Telegram/SourceFiles/codegen/common/CMakeLists.txt b/Telegram/SourceFiles/codegen/common/CMakeLists.txt new file mode 100644 index 000000000..abffc05ac --- /dev/null +++ b/Telegram/SourceFiles/codegen/common/CMakeLists.txt @@ -0,0 +1,8 @@ +add_library(codegen_common STATIC + basic_tokenized_file.cpp + checked_utf8_string.cpp + clean_file.cpp + cpp_file.cpp + logging.cpp +) +qt5_use_modules(codegen_common Core) diff --git a/Telegram/SourceFiles/codegen/common/basic_tokenized_file.cpp b/Telegram/SourceFiles/codegen/common/basic_tokenized_file.cpp index 9e215639b..c2816c40d 100644 --- a/Telegram/SourceFiles/codegen/common/basic_tokenized_file.cpp +++ b/Telegram/SourceFiles/codegen/common/basic_tokenized_file.cpp @@ -290,6 +290,8 @@ LogStream operator<<(LogStream &&stream, BasicTokenizedFile::Token::Type type) { case Type::Plus: value = "'+'"; break; case Type::Minus: value = "'-'"; break; case Type::Equals: value = "'='"; break; + case Type::And: value = "'and'"; break; + case Type::Or: value = "'or'"; break; case Type::Name: value = "'identifier'"; break; } return std::forward(stream) << value; diff --git a/Telegram/SourceFiles/codegen/emoji/CMakeLists.txt b/Telegram/SourceFiles/codegen/emoji/CMakeLists.txt new file mode 100644 index 000000000..babfd632d --- /dev/null +++ b/Telegram/SourceFiles/codegen/emoji/CMakeLists.txt @@ -0,0 +1,9 @@ +add_executable(codegen_emoji + data.cpp + generator.cpp + main.cpp + options.cpp + replaces.cpp +) +target_link_libraries(codegen_emoji codegen_common Qt5::Core Qt5::Gui) +qt5_use_modules(codegen_emoji Core) diff --git a/Telegram/SourceFiles/codegen/emoji/data.cpp b/Telegram/SourceFiles/codegen/emoji/data.cpp index 07557a0d3..e8c8dc1b3 100644 --- a/Telegram/SourceFiles/codegen/emoji/data.cpp +++ b/Telegram/SourceFiles/codegen/emoji/data.cpp @@ -19,15 +19,12 @@ Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ #include "codegen/emoji/data.h" +#include namespace codegen { namespace emoji { namespace { -using uint16 = quint16; -using uint32 = quint32; -using uint64 = quint64; - using std::vector; using std::map; using std::find; @@ -36,7 +33,7 @@ using std::move; using std::begin; using std::end; -using InputId = vector; +using InputId = vector; using InputCategory = vector; // copied from emoji_box.cpp @@ -83,7 +80,7 @@ Replace Replaces[] = { { { 0xD83DDE08U }, "}:)" }, }; -using ColorId = uint32; +using ColorId = uint32_t; ColorId Colors[] = { 0xD83CDFFBU, 0xD83CDFFCU, @@ -1703,11 +1700,11 @@ InputCategory Category7 = { constexpr auto kErrorBadData = 401; -void append(Id &id, uint32 code) { - if (auto first = static_cast((code >> 16) & 0xFFFFU)) { +void append(Id &id, uint32_t code) { + if (auto first = static_cast((code >> 16) & 0xFFFFU)) { id.append(QChar(first)); } - id.append(QChar(static_cast(code & 0xFFFFU))); + id.append(QChar(static_cast(code & 0xFFFFU))); } using VariatedIds = map; diff --git a/Telegram/SourceFiles/codegen/emoji/generator.cpp b/Telegram/SourceFiles/codegen/emoji/generator.cpp index 55c0f3a1f..35def25b5 100644 --- a/Telegram/SourceFiles/codegen/emoji/generator.cpp +++ b/Telegram/SourceFiles/codegen/emoji/generator.cpp @@ -123,11 +123,11 @@ QRect computeSourceRect(const QImage &image) { return result; } -uint32 Crc32Table[256]; +uint32_t Crc32Table[256]; class Crc32Initializer { public: Crc32Initializer() { - uint32 poly = 0x04C11DB7U; + uint32_t poly = 0x04C11DB7U; for (auto i = 0; i != 256; ++i) { Crc32Table[i] = reflect(i, 8) << 24; for (auto j = 0; j != 8; ++j) { @@ -138,8 +138,8 @@ public: } private: - uint32 reflect(uint32 val, char ch) { - uint32 result = 0; + uint32_t reflect(uint32_t val, char ch) { + uint32_t result = 0; for (int i = 1; i < (ch + 1); ++i) { if (val & 1) { result |= 1 << (ch - i); @@ -151,11 +151,11 @@ private: }; -uint32 countCrc32(const void *data, std::size_t size) { +uint32_t countCrc32(const void *data, std::size_t size) { static Crc32Initializer InitTable; auto buffer = static_cast(data); - auto result = uint32(0xFFFFFFFFU); + auto result = uint32_t(0xFFFFFFFFU); for (auto i = std::size_t(0); i != size; ++i) { result = (result >> 8) ^ Crc32Table[(result & 0xFFU) ^ buffer[i]]; } @@ -363,7 +363,7 @@ void Init() {\n\ \n\ Items.reserve(base::array_size(Data));\n\ for (auto &data : Data) {\n\ - Items.emplace_back(takeString(data.idSize), uint16(data.column), uint16(data.row), bool(data.postfixed), bool(data.variated), data.original ? &Items[data.original - 1] : nullptr, One::CreationTag());\n\ + Items.emplace_back(takeString(data.idSize), uint16_t(data.column), uint16_t(data.row), bool(data.postfixed), bool(data.variated), data.original ? &Items[data.original - 1] : nullptr, One::CreationTag());\n\ }\n\ InitReplacements();\n\ }\n\ @@ -806,9 +806,9 @@ bool Generator::writeReplacements() { QMap> byCharIndices; suggestionsSource_->stream() << "\ struct ReplacementStruct {\n\ - small emojiSize;\n\ - small replacementSize;\n\ - small wordsCount;\n\ + smallchar emojiSize;\n\ + smallchar replacementSize;\n\ + smallchar wordsCount;\n\ };\n\ \n\ const utf16char ReplacementData[] = {"; @@ -833,7 +833,7 @@ const utf16char ReplacementData[] = {"; } suggestionsSource_->stream() << " };\n\ \n\ -const small ReplacementWordLengths[] = {"; +const smallchar ReplacementWordLengths[] = {"; startBinary(); for (auto &replace : replaces_.list) { auto wordLengths = QStringList(); @@ -846,7 +846,7 @@ const small ReplacementWordLengths[] = {"; const ReplacementStruct ReplacementInitData[] = {\n"; for (auto &replace : replaces_.list) { suggestionsSource_->stream() << "\ - { small(" << replace.id.size() << "), small(" << replace.replacement.size() << "), small(" << replace.words.size() << ") },\n"; + { smallchar(" << replace.id.size() << "), smallchar(" << replace.replacement.size() << "), smallchar(" << replace.words.size() << ") },\n"; } suggestionsSource_->stream() << "};\n\ \n\ @@ -984,7 +984,7 @@ void Generator::writeIntBinary(common::CppFile *source, int data) { ++_binaryFullLength; } -void Generator::writeUintBinary(common::CppFile *source, uint32 data) { +void Generator::writeUintBinary(common::CppFile *source, uint32_t data) { if (_binaryFullLength > 0) source->stream() << ","; if (!_binaryCount++) { source->stream() << "\n"; diff --git a/Telegram/SourceFiles/codegen/emoji/generator.h b/Telegram/SourceFiles/codegen/emoji/generator.h index 974ad998e..a8e140b69 100644 --- a/Telegram/SourceFiles/codegen/emoji/generator.h +++ b/Telegram/SourceFiles/codegen/emoji/generator.h @@ -20,6 +20,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ #pragma once +#include #include #include #include @@ -31,8 +32,6 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org namespace codegen { namespace emoji { -using uint32 = unsigned int; - class Generator { public: Generator(const Options &options); @@ -66,7 +65,7 @@ private: void startBinary(); bool writeStringBinary(common::CppFile *source, const QString &string); void writeIntBinary(common::CppFile *source, int data); - void writeUintBinary(common::CppFile *source, uint32 data); + void writeUintBinary(common::CppFile *source, uint32_t data); const common::ProjectInfo &project_; int colorsCount_ = 0; diff --git a/Telegram/SourceFiles/codegen/lang/CMakeLists.txt b/Telegram/SourceFiles/codegen/lang/CMakeLists.txt new file mode 100644 index 000000000..109755402 --- /dev/null +++ b/Telegram/SourceFiles/codegen/lang/CMakeLists.txt @@ -0,0 +1,9 @@ +add_executable(codegen_lang + generator.cpp + main.cpp + options.cpp + parsed_file.cpp + processor.cpp +) +target_link_libraries(codegen_lang codegen_common Qt5::Core Qt5::Gui) +qt5_use_modules(codegen_lang Core Gui) diff --git a/Telegram/SourceFiles/codegen/lang/generator.cpp b/Telegram/SourceFiles/codegen/lang/generator.cpp index 125f6ef97..5b272a0cd 100644 --- a/Telegram/SourceFiles/codegen/lang/generator.cpp +++ b/Telegram/SourceFiles/codegen/lang/generator.cpp @@ -150,8 +150,8 @@ QString lang(LangKey key);\n\ for (auto &tagData : entry.tags) { auto &tag = tagData.tag; auto isPluralTag = isPlural && (tag == kPluralTag); - genericParams.push_back("lngtag_" + tag + ", " + (isPluralTag ? "float64 " : "const ResultString &") + tag + "__val"); - params.push_back("lngtag_" + tag + ", " + (isPluralTag ? "float64 " : "const QString &") + tag + "__val"); + genericParams.push_back("lngtag_" + tag + ", " + (isPluralTag ? "double " : "const ResultString &") + tag + "__val"); + params.push_back("lngtag_" + tag + ", " + (isPluralTag ? "double " : "const QString &") + tag + "__val"); if (isPluralTag) { plural = "\tauto plural = Lang::Plural(" + key + ", " + kPluralTag + "__val);\n"; applyTags.push_back("\tresult = Lang::ReplaceTag::Call(std::move(result), lt_" + tag + ", Lang::StartReplacements::Call(std::move(plural.replacement)));\n"); diff --git a/Telegram/SourceFiles/codegen/numbers/CMakeLists.txt b/Telegram/SourceFiles/codegen/numbers/CMakeLists.txt new file mode 100644 index 000000000..0c3e1fd69 --- /dev/null +++ b/Telegram/SourceFiles/codegen/numbers/CMakeLists.txt @@ -0,0 +1,9 @@ +add_executable(codegen_numbers + generator.cpp + main.cpp + options.cpp + parsed_file.cpp + processor.cpp +) +target_link_libraries(codegen_numbers codegen_common Qt5::Core) +qt5_use_modules(codegen_numbers Core) diff --git a/Telegram/SourceFiles/codegen/numbers/generator.cpp b/Telegram/SourceFiles/codegen/numbers/generator.cpp index b336b515a..9577fe5e4 100644 --- a/Telegram/SourceFiles/codegen/numbers/generator.cpp +++ b/Telegram/SourceFiles/codegen/numbers/generator.cpp @@ -51,7 +51,7 @@ bool Generator::writeSource() { QVector phoneNumberParse(const QString &number) {\n\ QVector result;\n\ \n\ - int32 len = number.size();\n\ + int32_t len = number.size();\n\ if (len > 0) switch (number.at(0).unicode()) {\n"; QString already; diff --git a/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py b/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py index 2e1a684ae..61d4e4798 100644 --- a/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py +++ b/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py @@ -311,7 +311,7 @@ with open(input_file) as f: prmsInit = []; prmsNames = []; if (hasFlags != ''): - funcsText += '\tenum class Flag : int32 {\n'; + funcsText += '\tenum class Flag : int32_t {\n'; maxbit = 0; parentFlagsCheck['MTP' + name] = {}; for paramName in conditionsList: @@ -356,12 +356,12 @@ with open(input_file) as f: funcsText += '\tMTP' + name + '(' + ', '.join(prmsStr) + ') : ' + ', '.join(prmsInit) + ' {\n\t}\n'; funcsText += '\n'; - funcsText += '\tuint32 innerLength() const;\n'; # count size + funcsText += '\tuint32_t innerLength() const;\n'; # count size if (isTemplate != ''): methodBodies += 'template \n' - methodBodies += 'uint32 MTP' + name + '::innerLength() const {\n'; + methodBodies += 'uint32_t MTP' + name + '::innerLength() const {\n'; else: - methodBodies += 'uint32 MTP' + name + '::innerLength() const {\n'; + methodBodies += 'uint32_t MTP' + name + '::innerLength() const {\n'; size = []; for k in prmsList: v = prms[k]; @@ -453,7 +453,7 @@ def addTextSerialize(lst, dct, dataLetter): conditions = data[6]; trivialConditions = data[7]; - result += 'void Serialize_' + name + '(MTPStringLogger &to, int32 stage, int32 lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32 iflag) {\n'; + result += 'void Serialize_' + name + '(MTPStringLogger &to, int32_t stage, int32_t lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32_t iflag) {\n'; if (len(conditions)): result += '\tMTP' + dataLetter + name + '::Flags flag(iflag);\n\n'; if (len(prms)): @@ -592,7 +592,7 @@ for restype in typesList: writeText = ''; if (hasFlags != ''): - dataText += '\tenum class Flag : int32 {\n'; + dataText += '\tenum class Flag : int32_t {\n'; maxbit = 0; parentFlagsCheck['MTPD' + name] = {}; for paramName in conditionsList: @@ -752,8 +752,8 @@ for restype in typesList: if (withData): typesText += getters; - typesText += '\n\tuint32 innerLength() const;\n'; # size method - methods += '\nuint32 MTP' + restype + '::innerLength() const {\n'; + typesText += '\n\tuint32_t innerLength() const;\n'; # size method + methods += '\nuint32_t MTP' + restype + '::innerLength() const {\n'; if (withType and sizeCases): methods += '\tswitch (_type) {\n'; methods += sizeCases; @@ -853,7 +853,7 @@ for childName in parentFlagsList: # manual types added here textSerializeMethods += '\ -void _serialize_rpc_result(MTPStringLogger &to, int32 stage, int32 lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32 iflag) {\n\ +void _serialize_rpc_result(MTPStringLogger &to, int32_t stage, int32_t lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32_t iflag) {\n\ if (stage) {\n\ to.add(",\\n").addSpaces(lev);\n\ } else {\n\ @@ -867,7 +867,7 @@ void _serialize_rpc_result(MTPStringLogger &to, int32 stage, int32 lev, Types &t }\n\ }\n\ \n\ -void _serialize_msg_container(MTPStringLogger &to, int32 stage, int32 lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32 iflag) {\n\ +void _serialize_msg_container(MTPStringLogger &to, int32_t stage, int32_t lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32_t iflag) {\n\ if (stage) {\n\ to.add(",\\n").addSpaces(lev);\n\ } else {\n\ @@ -880,7 +880,7 @@ void _serialize_msg_container(MTPStringLogger &to, int32 stage, int32 lev, Types }\n\ }\n\ \n\ -void _serialize_core_message(MTPStringLogger &to, int32 stage, int32 lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32 iflag) {\n\ +void _serialize_core_message(MTPStringLogger &to, int32_t stage, int32_t lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32_t iflag) {\n\ if (stage) {\n\ to.add(",\\n").addSpaces(lev);\n\ } else {\n\ @@ -966,7 +966,7 @@ enum {\n\ // Factory methods declaration\n\ ' + factories + '\n\ // Human-readable text serialization\n\ -void mtpTextSerializeType(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpPrime cons, uint32 level, mtpPrime vcons);\n' +void mtpTextSerializeType(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpPrime cons, uint32_t level, mtpPrime vcons);\n' source = '\ /*\n\ @@ -1007,12 +1007,12 @@ public:\n\ ' + methods + '\n\ \n\ using Types = QVector;\n\ -using StagesFlags = QVector;\n\ +using StagesFlags = QVector;\n\ \n\ ' + textSerializeMethods + '\n\ namespace {\n\ \n\ -using TextSerializer = void (*)(MTPStringLogger &to, int32 stage, int32 lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32 iflag);\n\ +using TextSerializer = void (*)(MTPStringLogger &to, int32_t stage, int32_t lev, Types &types, Types &vtypes, StagesFlags &stages, StagesFlags &flags, const mtpPrime *start, const mtpPrime *end, int32_t iflag);\n\ using TextSerializers = QMap;\n\ \n\ QMap createTextSerializers() {\n\ @@ -1025,17 +1025,17 @@ QMap createTextSerializers() {\n\ \n\ } // namespace\n\ \n\ -void mtpTextSerializeType(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpPrime cons, uint32 level, mtpPrime vcons) {\n\ +void mtpTextSerializeType(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpPrime cons, uint32_t level, mtpPrime vcons) {\n\ static auto serializers = createTextSerializers();\n\ \n\ QVector types, vtypes;\n\ - QVector stages, flags;\n\ + QVector stages, flags;\n\ types.reserve(20); vtypes.reserve(20); stages.reserve(20); flags.reserve(20);\n\ types.push_back(mtpTypeId(cons)); vtypes.push_back(mtpTypeId(vcons)); stages.push_back(0); flags.push_back(0);\n\ \n\ const mtpPrime *start = from;\n\ mtpTypeId type = cons, vtype = vcons;\n\ - int32 stage = 0, flag = 0;\n\ + int32_t stage = 0, flag = 0;\n\ \n\ while (!types.isEmpty()) {\n\ type = types.back();\n\ @@ -1052,7 +1052,7 @@ void mtpTextSerializeType(MTPStringLogger &to, const mtpPrime *&from, const mtpP start = ++from;\n\ }\n\ \n\ - int32 lev = level + types.size() - 1;\n\ + int32_t lev = level + types.size() - 1;\n\ auto it = serializers.constFind(type);\n\ if (it != serializers.cend()) {\n\ (*it.value())(to, stage, lev, types, vtypes, stages, flags, start, end, flag);\n\ diff --git a/Telegram/SourceFiles/codegen/style/CMakeLists.txt b/Telegram/SourceFiles/codegen/style/CMakeLists.txt new file mode 100644 index 000000000..14414e8b2 --- /dev/null +++ b/Telegram/SourceFiles/codegen/style/CMakeLists.txt @@ -0,0 +1,11 @@ +add_executable(codegen_style + generator.cpp + main.cpp + module.cpp + options.cpp + parsed_file.cpp + processor.cpp + structure_types.cpp +) +target_link_libraries(codegen_style codegen_common Qt5::Core Qt5::Gui) +qt5_use_modules(codegen_style Core Gui) diff --git a/Telegram/SourceFiles/codegen/style/generator.cpp b/Telegram/SourceFiles/codegen/style/generator.cpp index 7d01c6c52..0b9c03b8f 100644 --- a/Telegram/SourceFiles/codegen/style/generator.cpp +++ b/Telegram/SourceFiles/codegen/style/generator.cpp @@ -46,7 +46,7 @@ constexpr int kErrorBadIconFormat = 862; class Crc32Table { public: Crc32Table() { - quint32 poly = 0x04c11db7; + uint32_t poly = 0x04c11db7; for (auto i = 0; i != 256; ++i) { _data[i] = reflect(i, 8) << 24; for (auto j = 0; j != 8; ++j) { @@ -56,13 +56,13 @@ public: } } - inline quint32 operator[](int index) const { + inline uint32_t operator[](int index) const { return _data[index]; } private: - quint32 reflect(quint32 val, char ch) { - quint32 result = 0; + uint32_t reflect(uint32_t val, char ch) { + uint32_t result = 0; for (int i = 1; i < (ch + 1); ++i) { if (val & 1) { result |= 1 << (ch - i); @@ -72,21 +72,21 @@ private: return result; } - quint32 _data[256]; + uint32_t _data[256]; }; -qint32 hashCrc32(const void *data, int len) { +int32_t hashCrc32(const void *data, int len) { static Crc32Table table; const uchar *buffer = static_cast(data); - quint32 crc = 0xffffffff; + uint32_t crc = 0xffffffff; for (int i = 0; i != len; ++i) { crc = (crc >> 8) ^ table[(crc & 0xFF) ^ buffer[i]]; } - return static_cast(crc ^ 0xffffffff); + return static_cast(crc ^ 0xffffffff); } char hexChar(uchar ch) { @@ -504,7 +504,7 @@ public:\n\ return *this;\n\ }\n\ \n\ - static int32 Checksum();\n\ + static int32_t Checksum();\n\ \n\ ~palette() {\n\ clear();\n\ @@ -809,7 +809,7 @@ void palette::finalize() {\n\ source_->stream() << "\ }\n\ \n\ -int32 palette::Checksum() {\n\ +int32_t palette::Checksum() {\n\ return " << checksum << ";\n\ }\n"; @@ -1178,7 +1178,7 @@ QByteArray iconMaskValueSize(int width, int height) { { QDataStream stream(&result, QIODevice::Append); stream.setVersion(QDataStream::Qt_5_1); - stream << qint32(width) << qint32(height); + stream << int32_t(width) << int32_t(height); } return result; } diff --git a/Telegram/SourceFiles/codegen/style/parsed_file.h b/Telegram/SourceFiles/codegen/style/parsed_file.h index 8bf3137e1..564d93be9 100644 --- a/Telegram/SourceFiles/codegen/style/parsed_file.h +++ b/Telegram/SourceFiles/codegen/style/parsed_file.h @@ -23,7 +23,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include #include #include -#include +#include #include "codegen/common/basic_tokenized_file.h" #include "codegen/style/options.h" #include "codegen/style/module.h" diff --git a/Telegram/SourceFiles/config.h b/Telegram/SourceFiles/config.h index 633c4e4a6..ac36ba11b 100644 --- a/Telegram/SourceFiles/config.h +++ b/Telegram/SourceFiles/config.h @@ -134,11 +134,11 @@ enum { ChoosePeerByDragTimeout = 1000, // 1 second mouse not moved to choose dialog when dragging a file }; -inline bool isNotificationsUser(uint64 id) { +inline bool isNotificationsUser(uint64_t id) { return (id == 333000) || (id == ServiceUserId); } -inline bool isServiceUser(uint64 id) { +inline bool isServiceUser(uint64_t id) { return !(id % 1000);// (id == 333000) || (id == ServiceUserId); } @@ -247,7 +247,7 @@ w/CVnbwQOw0g5GBwwFV3r0uTTvy44xx8XXxk+Qknu4eBCsmrAFNnAgMBAAE=\n\ #ifdef CUSTOM_API_ID #include "../../../TelegramPrivate/custom_api_id.h" // Custom API id and API hash #else -static const int32 ApiId = 17349; +static const int32_t ApiId = 17349; static const char *ApiHash = "344583e45741c457fe1862106095a5eb"; #endif diff --git a/Telegram/SourceFiles/core/basic_types.h b/Telegram/SourceFiles/core/basic_types.h index e6cdbfa48..2259cbba0 100644 --- a/Telegram/SourceFiles/core/basic_types.h +++ b/Telegram/SourceFiles/core/basic_types.h @@ -51,15 +51,7 @@ void as_const(const T&&) = delete; #include "base/ordered_set.h" -//using uchar = unsigned char; // Qt has uchar -using int16 = qint16; -using uint16 = quint16; -using int32 = qint32; -using uint32 = quint32; -using int64 = qint64; -using uint64 = quint64; -using float32 = float; -using float64 = double; +#include #define qsl(s) QStringLiteral(s) #define qstr(s) QLatin1String(s, sizeof(s) - 1) diff --git a/Telegram/SourceFiles/core/click_handler_types.h b/Telegram/SourceFiles/core/click_handler_types.h index 04f7ddb8f..d691408eb 100644 --- a/Telegram/SourceFiles/core/click_handler_types.h +++ b/Telegram/SourceFiles/core/click_handler_types.h @@ -157,7 +157,7 @@ private: class MentionNameClickHandler : public ClickHandler { public: - MentionNameClickHandler(QString text, UserId userId, uint64 accessHash) + MentionNameClickHandler(QString text, UserId userId, uint64_t accessHash) : _text(text) , _userId(userId) , _accessHash(accessHash) { @@ -172,7 +172,7 @@ public: private: QString _text; UserId _userId; - uint64 _accessHash; + uint64_t _accessHash; }; diff --git a/Telegram/SourceFiles/core/file_utilities.cpp b/Telegram/SourceFiles/core/file_utilities.cpp index 0045d449c..ea1f5ec69 100644 --- a/Telegram/SourceFiles/core/file_utilities.cpp +++ b/Telegram/SourceFiles/core/file_utilities.cpp @@ -71,7 +71,7 @@ QString filedialogDefaultName(const QString &prefix, const QString &extension, c QString filedialogNextFilename(const QString &name, const QString &cur, const QString &path) { QDir dir(path.isEmpty() ? cDialogLastPath() : path); - int32 extIndex = name.lastIndexOf('.'); + int32_t extIndex = name.lastIndexOf('.'); QString prefix = name, extension; if (extIndex >= 0) { extension = name.mid(extIndex); diff --git a/Telegram/SourceFiles/core/utils.cpp b/Telegram/SourceFiles/core/utils.cpp index f986174c4..4478d0601 100644 --- a/Telegram/SourceFiles/core/utils.cpp +++ b/Telegram/SourceFiles/core/utils.cpp @@ -36,7 +36,7 @@ extern "C" { #include "application.h" #include "platform/platform_specific.h" -uint64 _SharedMemoryLocation[4] = { 0x00, 0x01, 0x02, 0x03 }; +uint64_t _SharedMemoryLocation[4] = { 0x00, 0x01, 0x02, 0x03 }; #ifdef Q_OS_WIN #elif defined Q_OS_MAC @@ -50,14 +50,14 @@ uint64 _SharedMemoryLocation[4] = { 0x00, 0x01, 0x02, 0x03 }; // Base types compile-time check static_assert(sizeof(char) == 1, "Basic types size check failed"); static_assert(sizeof(uchar) == 1, "Basic types size check failed"); -static_assert(sizeof(int16) == 2, "Basic types size check failed"); -static_assert(sizeof(uint16) == 2, "Basic types size check failed"); -static_assert(sizeof(int32) == 4, "Basic types size check failed"); -static_assert(sizeof(uint32) == 4, "Basic types size check failed"); -static_assert(sizeof(int64) == 8, "Basic types size check failed"); -static_assert(sizeof(uint64) == 8, "Basic types size check failed"); -static_assert(sizeof(float32) == 4, "Basic types size check failed"); -static_assert(sizeof(float64) == 8, "Basic types size check failed"); +static_assert(sizeof(int16_t) == 2, "Basic types size check failed"); +static_assert(sizeof(uint16_t) == 2, "Basic types size check failed"); +static_assert(sizeof(int32_t) == 4, "Basic types size check failed"); +static_assert(sizeof(uint32_t) == 4, "Basic types size check failed"); +static_assert(sizeof(int64_t) == 8, "Basic types size check failed"); +static_assert(sizeof(uint64_t) == 8, "Basic types size check failed"); +static_assert(sizeof(float) == 4, "Basic types size check failed"); +static_assert(sizeof(double) == 8, "Basic types size check failed"); static_assert(sizeof(mtpPrime) == 4, "Basic types size check failed"); static_assert(sizeof(MTPint) == 4, "Basic types size check failed"); static_assert(sizeof(MTPlong) == 8, "Basic types size check failed"); @@ -69,10 +69,10 @@ static_assert(sizeof(MTPdouble) == 8, "Basic types size check failed"); namespace { QReadWriteLock unixtimeLock; - volatile int32 unixtimeDelta = 0; + volatile int32_t unixtimeDelta = 0; volatile bool unixtimeWasSet = false; - volatile uint64 _msgIdStart, _msgIdLocal = 0, _msgIdMsStart; - int32 _reqId = 0; + volatile uint64_t _msgIdStart, _msgIdLocal = 0, _msgIdMsStart; + int32_t _reqId = 0; void _initMsgIdConstants() { #ifdef Q_OS_WIN @@ -84,12 +84,12 @@ namespace { #else timespec ts; clock_gettime(CLOCK_REALTIME, &ts); - _msgIdMsStart = 1000000000 * uint64(ts.tv_sec) + uint64(ts.tv_nsec); + _msgIdMsStart = 1000000000 * uint64_t(ts.tv_sec) + uint64_t(ts.tv_nsec); #endif - uint32 msgIdRand; - memset_rand(&msgIdRand, sizeof(uint32)); - _msgIdStart = (((uint64)((uint32)unixtime()) << 32) | (uint64)msgIdRand); + uint32_t msgIdRand; + memset_rand(&msgIdRand, sizeof(uint32_t)); + _msgIdStart = (((uint64_t)((uint32_t)unixtime()) << 32) | (uint64_t)msgIdRand); } } @@ -106,7 +106,7 @@ void unixtimeInit() { _initMsgIdConstants(); } -void unixtimeSet(int32 serverTime, bool force) { +void unixtimeSet(int32_t serverTime, bool force) { { QWriteLocker locker(&unixtimeLock); if (force) { @@ -204,10 +204,10 @@ namespace { return 0; } - float64 _msFreq; - float64 _msgIdCoef; + double _msFreq; + double _msgIdCoef; TimeMs _msStart = 0, _msAddToMsStart = 0, _msAddToUnixtime = 0; - int32 _timeStart = 0; + int32_t _timeStart = 0; class _MsInitializer { public: @@ -215,30 +215,30 @@ namespace { #ifdef Q_OS_WIN LARGE_INTEGER li; QueryPerformanceFrequency(&li); - _msFreq = 1000. / float64(li.QuadPart); + _msFreq = 1000. / double(li.QuadPart); // 0xFFFF0000L istead of 0x100000000L to make msgId grow slightly slower, than unixtime and we had time to reconfigure - _msgIdCoef = float64(0xFFFF0000L) / float64(li.QuadPart); + _msgIdCoef = double(0xFFFF0000L) / double(li.QuadPart); QueryPerformanceCounter(&li); _msStart = li.QuadPart; #elif defined Q_OS_MAC mach_timebase_info_data_t tb = { 0, 0 }; mach_timebase_info(&tb); - _msFreq = (float64(tb.numer) / tb.denom) / 1000000.; + _msFreq = (double(tb.numer) / tb.denom) / 1000000.; - _msgIdCoef = _msFreq * (float64(0xFFFF0000L) / 1000.); + _msgIdCoef = _msFreq * (double(0xFFFF0000L) / 1000.); _msStart = mach_absolute_time(); #else timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); //_msFreq = 1 / 1000000.; - _msgIdCoef = float64(0xFFFF0000L) / 1000000000.; + _msgIdCoef = double(0xFFFF0000L) / 1000000000.; _msStart = 1000LL * static_cast(ts.tv_sec) + (static_cast(ts.tv_nsec) / 1000000LL); #endif _timeStart = myunixtime(); - srand((uint32)(_msStart & 0xFFFFFFFFL)); + srand((uint32_t)(_msStart & 0xFFFFFFFFL)); } }; @@ -308,7 +308,7 @@ namespace ThirdParty { av_lockmgr_register(nullptr); CRYPTO_cleanup_all_ex_data(); - FIPS_mode_set(0); + // FIPS_mode_set(0); ENGINE_cleanup(); CONF_modules_unload(1); ERR_remove_state(0); @@ -356,19 +356,19 @@ TimeMs getms(bool checked) { #endif } -uint64 msgid() { +uint64_t msgid() { #ifdef Q_OS_WIN LARGE_INTEGER li; QueryPerformanceCounter(&li); - uint64 result = _msgIdStart + (uint64)floor((li.QuadPart - _msgIdMsStart) * _msgIdCoef); + uint64_t result = _msgIdStart + (uint64_t)floor((li.QuadPart - _msgIdMsStart) * _msgIdCoef); #elif defined Q_OS_MAC - uint64 msCount = mach_absolute_time(); - uint64 result = _msgIdStart + (uint64)floor((msCount - _msgIdMsStart) * _msgIdCoef); + uint64_t msCount = mach_absolute_time(); + uint64_t result = _msgIdStart + (uint64_t)floor((msCount - _msgIdMsStart) * _msgIdCoef); #else timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); - uint64 msCount = 1000000000 * uint64(ts.tv_sec) + uint64(ts.tv_nsec); - uint64 result = _msgIdStart + (uint64)floor((msCount - _msgIdMsStart) * _msgIdCoef); + uint64_t msCount = 1000000000 * uint64_t(ts.tv_sec) + uint64_t(ts.tv_nsec); + uint64_t result = _msgIdStart + (uint64_t)floor((msCount - _msgIdMsStart) * _msgIdCoef); #endif result &= ~0x03L; @@ -376,7 +376,7 @@ uint64 msgid() { return result + (_msgIdLocal += 4); } -int32 reqid() { +int32_t reqid() { QWriteLocker locker(&unixtimeLock); if (_reqId == INT_MAX) { _reqId = 0; @@ -387,14 +387,14 @@ int32 reqid() { // crc32 hash, taken somewhere from the internet namespace { - uint32 _crc32Table[256]; + uint32_t _crc32Table[256]; class _Crc32Initializer { public: _Crc32Initializer() { - uint32 poly = 0x04c11db7; - for (uint32 i = 0; i < 256; ++i) { + uint32_t poly = 0x04c11db7; + for (uint32_t i = 0; i < 256; ++i) { _crc32Table[i] = reflect(i, 8) << 24; - for (uint32 j = 0; j < 8; ++j) { + for (uint32_t j = 0; j < 8; ++j) { _crc32Table[i] = (_crc32Table[i] << 1) ^ (_crc32Table[i] & (1 << 31) ? poly : 0); } _crc32Table[i] = reflect(_crc32Table[i], 32); @@ -402,8 +402,8 @@ namespace { } private: - uint32 reflect(uint32 val, char ch) { - uint32 result = 0; + uint32_t reflect(uint32_t val, char ch) { + uint32_t result = 0; for (int i = 1; i < (ch + 1); ++i) { if (val & 1) { result |= 1 << (ch - i); @@ -415,39 +415,39 @@ namespace { }; } -int32 hashCrc32(const void *data, uint32 len) { +int32_t hashCrc32(const void *data, uint32_t len) { static _Crc32Initializer _crc32Initializer; const uchar *buf = (const uchar *)data; - uint32 crc(0xffffffff); - for (uint32 i = 0; i < len; ++i) { + uint32_t crc(0xffffffff); + for (uint32_t i = 0; i < len; ++i) { crc = (crc >> 8) ^ _crc32Table[(crc & 0xFF) ^ buf[i]]; } return crc ^ 0xffffffff; } -int32 *hashSha1(const void *data, uint32 len, void *dest) { - return (int32*)SHA1((const uchar*)data, (size_t)len, (uchar*)dest); +int32_t *hashSha1(const void *data, uint32_t len, void *dest) { + return (int32_t*)SHA1((const uchar*)data, (size_t)len, (uchar*)dest); } -int32 *hashSha256(const void *data, uint32 len, void *dest) { - return (int32*)SHA256((const uchar*)data, (size_t)len, (uchar*)dest); +int32_t *hashSha256(const void *data, uint32_t len, void *dest) { + return (int32_t*)SHA256((const uchar*)data, (size_t)len, (uchar*)dest); } // md5 hash, taken somewhere from the internet namespace { - inline void _md5_decode(uint32 *output, const uchar *input, uint32 len) { - for (uint32 i = 0, j = 0; j < len; i++, j += 4) { - output[i] = ((uint32)input[j]) | (((uint32)input[j + 1]) << 8) | (((uint32)input[j + 2]) << 16) | (((uint32)input[j + 3]) << 24); + inline void _md5_decode(uint32_t *output, const uchar *input, uint32_t len) { + for (uint32_t i = 0, j = 0; j < len; i++, j += 4) { + output[i] = ((uint32_t)input[j]) | (((uint32_t)input[j + 1]) << 8) | (((uint32_t)input[j + 2]) << 16) | (((uint32_t)input[j + 3]) << 24); } } - inline void _md5_encode(uchar *output, const uint32 *input, uint32 len) { - for (uint32 i = 0, j = 0; j < len; i++, j += 4) { + inline void _md5_encode(uchar *output, const uint32_t *input, uint32_t len) { + for (uint32_t i = 0, j = 0; j < len; i++, j += 4) { output[j + 0] = (input[i]) & 0xFF; output[j + 1] = (input[i] >> 8) & 0xFF; output[j + 2] = (input[i] >> 16) & 0xFF; @@ -455,39 +455,39 @@ namespace { } } - inline uint32 _md5_rotate_left(uint32 x, int n) { + inline uint32_t _md5_rotate_left(uint32_t x, int n) { return (x << n) | (x >> (32 - n)); } - inline uint32 _md5_F(uint32 x, uint32 y, uint32 z) { + inline uint32_t _md5_F(uint32_t x, uint32_t y, uint32_t z) { return (x & y) | (~x & z); } - inline uint32 _md5_G(uint32 x, uint32 y, uint32 z) { + inline uint32_t _md5_G(uint32_t x, uint32_t y, uint32_t z) { return (x & z) | (y & ~z); } - inline uint32 _md5_H(uint32 x, uint32 y, uint32 z) { + inline uint32_t _md5_H(uint32_t x, uint32_t y, uint32_t z) { return x ^ y ^ z; } - inline uint32 _md5_I(uint32 x, uint32 y, uint32 z) { + inline uint32_t _md5_I(uint32_t x, uint32_t y, uint32_t z) { return y ^ (x | ~z); } - inline void _md5_FF(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 ac) { + inline void _md5_FF(uint32_t &a, uint32_t b, uint32_t c, uint32_t d, uint32_t x, uint32_t s, uint32_t ac) { a = _md5_rotate_left(a + _md5_F(b, c, d) + x + ac, s) + b; } - inline void _md5_GG(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 ac) { + inline void _md5_GG(uint32_t &a, uint32_t b, uint32_t c, uint32_t d, uint32_t x, uint32_t s, uint32_t ac) { a = _md5_rotate_left(a + _md5_G(b, c, d) + x + ac, s) + b; } - inline void _md5_HH(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 ac) { + inline void _md5_HH(uint32_t &a, uint32_t b, uint32_t c, uint32_t d, uint32_t x, uint32_t s, uint32_t ac) { a = _md5_rotate_left(a + _md5_H(b, c, d) + x + ac, s) + b; } - inline void _md5_II(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 ac) { + inline void _md5_II(uint32_t &a, uint32_t b, uint32_t c, uint32_t d, uint32_t x, uint32_t s, uint32_t ac) { a = _md5_rotate_left(a + _md5_I(b, c, d) + x + ac, s) + b; } @@ -498,13 +498,13 @@ namespace { }; } -HashMd5::HashMd5(const void *input, uint32 length) : _finalized(false) { +HashMd5::HashMd5(const void *input, uint32_t length) : _finalized(false) { init(); if (input && length > 0) feed(input, length); } -void HashMd5::feed(const void *input, uint32 length) { - uint32 index = _count[0] / 8 % _md5_block_size; +void HashMd5::feed(const void *input, uint32_t length) { + uint32_t index = _count[0] / 8 % _md5_block_size; const uchar *buf = (const uchar *)input; @@ -513,9 +513,9 @@ void HashMd5::feed(const void *input, uint32 length) { } _count[1] += (length >> 29); - uint32 firstpart = 64 - index; + uint32_t firstpart = 64 - index; - uint32 i; + uint32_t i; if (length >= firstpart) { memcpy(&_buffer[index], buf, firstpart); @@ -533,9 +533,9 @@ void HashMd5::feed(const void *input, uint32 length) { memcpy(&_buffer[index], &buf[i], length - i); } -int32 *HashMd5::result() { +int32_t *HashMd5::result() { if (!_finalized) finalize(); - return (int32*)_digest; + return (int32_t*)_digest; } void HashMd5::init() { @@ -553,7 +553,7 @@ void HashMd5::finalize() { uchar bits[8]; _md5_encode(bits, _count, 8); - uint32 index = _count[0] / 8 % 64, paddingLen = (index < 56) ? (56 - index) : (120 - index); + uint32_t index = _count[0] / 8 % 64, paddingLen = (index < 56) ? (56 - index) : (120 - index); feed(_md5_padding, paddingLen); feed(bits, 8); @@ -564,7 +564,7 @@ void HashMd5::finalize() { } void HashMd5::transform(const uchar *block) { - uint32 a = _state[0], b = _state[1], c = _state[2], d = _state[3], x[16]; + uint32_t a = _state[0], b = _state[1], c = _state[2], d = _state[3], x[16]; _md5_decode(x, block, _md5_block_size); _md5_FF(a, b, c, d, x[0] , 7 , 0xd76aa478); @@ -641,14 +641,14 @@ void HashMd5::transform(const uchar *block) { _state[3] += d; } -int32 *hashMd5(const void *data, uint32 len, void *dest) { +int32_t *hashMd5(const void *data, uint32_t len, void *dest) { HashMd5 md5(data, len); memcpy(dest, md5.result(), 16); - return (int32*)dest; + return (int32_t*)dest; } -char *hashMd5Hex(const int32 *hashmd5, void *dest) { +char *hashMd5Hex(const int32_t *hashmd5, void *dest) { char *md5To = (char*)dest; const uchar *res = (const uchar*)hashmd5; @@ -661,7 +661,7 @@ char *hashMd5Hex(const int32 *hashmd5, void *dest) { return md5To; } -void memset_rand(void *data, uint32 len) { +void memset_rand(void *data, uint32_t len) { Assert(_sslInited); RAND_bytes((uchar*)data, len); } @@ -669,11 +669,11 @@ void memset_rand(void *data, uint32 len) { namespace { QMap fastRusEng; QHash fastLetterRusEng; - QMap fastDoubleLetterRusEng; + QMap fastDoubleLetterRusEng; QHash fastRusKeyboardSwitch; } -QString translitLetterRusEng(QChar letter, QChar next, int32 &toSkip) { +QString translitLetterRusEng(QChar letter, QChar next, int32_t &toSkip) { if (fastDoubleLetterRusEng.isEmpty()) { fastDoubleLetterRusEng.insert((QString::fromUtf8("Ы").at(0).unicode() << 16) | QString::fromUtf8("й").at(0).unicode(), qsl("Y")); fastDoubleLetterRusEng.insert((QString::fromUtf8("и").at(0).unicode() << 16) | QString::fromUtf8("я").at(0).unicode(), qsl("ia")); @@ -682,7 +682,7 @@ QString translitLetterRusEng(QChar letter, QChar next, int32 &toSkip) { fastDoubleLetterRusEng.insert((QString::fromUtf8("ы").at(0).unicode() << 16) | QString::fromUtf8("й").at(0).unicode(), qsl("y")); fastDoubleLetterRusEng.insert((QString::fromUtf8("ь").at(0).unicode() << 16) | QString::fromUtf8("е").at(0).unicode(), qsl("ye")); } - QMap::const_iterator i = fastDoubleLetterRusEng.constFind((letter.unicode() << 16) | next.unicode()); + QMap::const_iterator i = fastDoubleLetterRusEng.constFind((letter.unicode() << 16) | next.unicode()); if (i != fastDoubleLetterRusEng.cend()) { toSkip = 2; return i.value(); @@ -795,7 +795,7 @@ QString translitRusEng(const QString &rus) { QString result; result.reserve(rus.size() * 2); - int32 toSkip = 0; + int32_t toSkip = 0; for (QString::const_iterator i = rus.cbegin(), e = rus.cend(); i != e; i += toSkip) { result += translitLetterRusEng(*i, (i + 1 == e) ? ' ' : *(i + 1), toSkip); } diff --git a/Telegram/SourceFiles/core/utils.h b/Telegram/SourceFiles/core/utils.h index 3c46326dd..bb1c0a462 100644 --- a/Telegram/SourceFiles/core/utils.h +++ b/Telegram/SourceFiles/core/utils.h @@ -185,9 +185,9 @@ inline void InvokeQueued(QObject *context, Lambda &&lambda) { QObject::connect(&proxy, &QObject::destroyed, context, std::forward(lambda), Qt::QueuedConnection); } -static const int32 ScrollMax = INT_MAX; +static const int32_t ScrollMax = INT_MAX; -extern uint64 _SharedMemoryLocation[]; +extern uint64_t _SharedMemoryLocation[]; template T *SharedMemoryLocation() { static_assert(N < 4, "Only 4 shared memory locations!"); @@ -253,17 +253,17 @@ private: }; class MTPint; -using TimeId = int32; +using TimeId = int32_t; TimeId myunixtime(); void unixtimeInit(); void unixtimeSet(TimeId servertime, bool force = false); TimeId unixtime(); TimeId fromServerTime(const MTPint &serverTime); void toServerTime(const TimeId &clientTime, MTPint &outServerTime); -uint64 msgid(); -int32 reqid(); +uint64_t msgid(); +int32_t reqid(); -inline QDateTime date(int32 time = -1) { +inline QDateTime date(int32_t time = -1) { QDateTime result; if (time >= 0) result.setTime_t(time); return result; @@ -294,17 +294,17 @@ void finish(); } -using TimeMs = int64; +using TimeMs = int64_t; // @todo use std::chrono::milliseconds bool checkms(); // returns true if time has changed TimeMs getms(bool checked = false); -const static uint32 _md5_block_size = 64; +const static uint32_t _md5_block_size = 64; class HashMd5 { public: - HashMd5(const void *input = 0, uint32 length = 0); - void feed(const void *input, uint32 length); - int32 *result(); + HashMd5(const void *input = 0, uint32_t length = 0); + void feed(const void *input, uint32_t length); + int32_t *result(); private: @@ -314,37 +314,37 @@ private: bool _finalized; uchar _buffer[_md5_block_size]; - uint32 _count[2]; - uint32 _state[4]; + uint32_t _count[2]; + uint32_t _state[4]; uchar _digest[16]; }; -int32 hashCrc32(const void *data, uint32 len); +int32_t hashCrc32(const void *data, uint32_t len); -int32 *hashSha1(const void *data, uint32 len, void *dest); // dest - ptr to 20 bytes, returns (int32*)dest +int32_t *hashSha1(const void *data, uint32_t len, void *dest); // dest - ptr to 20 bytes, returns (int32_t*)dest inline std::array hashSha1(const void *data, int size) { auto result = std::array(); hashSha1(data, size, result.data()); return result; } -int32 *hashSha256(const void *data, uint32 len, void *dest); // dest - ptr to 32 bytes, returns (int32*)dest +int32_t *hashSha256(const void *data, uint32_t len, void *dest); // dest - ptr to 32 bytes, returns (int32_t*)dest inline std::array hashSha256(const void *data, int size) { auto result = std::array(); hashSha256(data, size, result.data()); return result; } -int32 *hashMd5(const void *data, uint32 len, void *dest); // dest = ptr to 16 bytes, returns (int32*)dest +int32_t *hashMd5(const void *data, uint32_t len, void *dest); // dest = ptr to 16 bytes, returns (int32_t*)dest inline std::array hashMd5(const void *data, int size) { auto result = std::array(); hashMd5(data, size, result.data()); return result; } -char *hashMd5Hex(const int32 *hashmd5, void *dest); // dest = ptr to 32 bytes, returns (char*)dest -inline char *hashMd5Hex(const void *data, uint32 len, void *dest) { // dest = ptr to 32 bytes, returns (char*)dest +char *hashMd5Hex(const int32_t *hashmd5, void *dest); // dest = ptr to 32 bytes, returns (char*)dest +inline char *hashMd5Hex(const void *data, uint32_t len, void *dest) { // dest = ptr to 32 bytes, returns (char*)dest return hashMd5Hex(HashMd5(data, len).result(), dest); } inline std::array hashMd5Hex(const void *data, int size) { @@ -354,7 +354,7 @@ inline std::array hashMd5Hex(const void *data, int size) { } // good random (using openssl implementation) -void memset_rand(void *data, uint32 len); +void memset_rand(void *data, uint32_t len); template T rand_value() { T result; @@ -362,7 +362,7 @@ T rand_value() { return result; } -inline void memset_rand_bad(void *data, uint32 len) { +inline void memset_rand_bad(void *data, uint32_t len) { for (uchar *i = reinterpret_cast(data), *e = i + len; i != e; ++i) { *i = uchar(rand() & 0xFF); } @@ -402,9 +402,9 @@ private: }; -inline QString fromUtf8Safe(const char *str, int32 size = -1) { +inline QString fromUtf8Safe(const char *str, int32_t size = -1) { if (!str || !size) return QString(); - if (size < 0) size = int32(strlen(str)); + if (size < 0) size = int32_t(strlen(str)); QString result(QString::fromUtf8(str, size)); QByteArray back = result.toUtf8(); if (back.size() != size || memcmp(back.constData(), str, size)) return QString::fromLocal8Bit(str, size); @@ -418,7 +418,7 @@ inline QString fromUtf8Safe(const QByteArray &str) { static const QRegularExpression::PatternOptions reMultiline(QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); template -inline T snap(const T &v, const T &_min, const T &_max) { +inline T snap(const T &v, const T &_min, const T &_max) { // @todo std::clamp() return (v < _min) ? _min : ((v > _max) ? _max : v); } @@ -474,7 +474,7 @@ enum DBIConnectionType { struct ProxyData { QString host; - uint32 port = 0; + uint32_t port = 0; QString user, password; }; @@ -508,10 +508,10 @@ enum DBIPeerReportSpamStatus { }; template -inline QString strMakeFromLetters(const uint32 (&letters)[Size]) { +inline QString strMakeFromLetters(const uint32_t (&letters)[Size]) { QString result; result.reserve(Size); - for (int32 i = 0; i < Size; ++i) { + for (int32_t i = 0; i < Size; ++i) { result.push_back(QChar((((letters[i] >> 16) & 0xFF) << 8) | (letters[i] & 0xFF))); } return result; @@ -552,13 +552,13 @@ inline int rowscount(int fullCount, int countPerRow) { inline int floorclamp(int value, int step, int lowest, int highest) { return qMin(qMax(value / step, lowest), highest); } -inline int floorclamp(float64 value, int step, int lowest, int highest) { +inline int floorclamp(double value, int step, int lowest, int highest) { return qMin(qMax(static_cast(std::floor(value / step)), lowest), highest); } inline int ceilclamp(int value, int step, int lowest, int highest) { return qMax(qMin((value + step - 1) / step, highest), lowest); } -inline int ceilclamp(float64 value, int32 step, int32 lowest, int32 highest) { +inline int ceilclamp(double value, int32_t step, int32_t lowest, int32_t highest) { return qMax(qMin(static_cast(std::ceil(value / step)), highest), lowest); } @@ -580,10 +580,10 @@ enum ShowLayerOption { using ShowLayerOptions = base::flags; inline constexpr auto is_flag_type(ShowLayerOption) { return true; }; -static int32 FullArcLength = 360 * 16; -static int32 QuarterArcLength = (FullArcLength / 4); -static int32 MinArcLength = (FullArcLength / 360); -static int32 AlmostFullArcLength = (FullArcLength - MinArcLength); +static int32_t FullArcLength = 360 * 16; +static int32_t QuarterArcLength = (FullArcLength / 4); +static int32_t MinArcLength = (FullArcLength / 360); +static int32_t AlmostFullArcLength = (FullArcLength - MinArcLength); template inline QSharedPointer MakeShared(Args&&... args) { diff --git a/Telegram/SourceFiles/core/version.h b/Telegram/SourceFiles/core/version.h index 3f6ba8502..45fccf8b8 100644 --- a/Telegram/SourceFiles/core/version.h +++ b/Telegram/SourceFiles/core/version.h @@ -20,11 +20,12 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ #pragma once -#include "core/utils.h" +#include +// #include "core/utils.h" #define BETA_VERSION_MACRO (0ULL) constexpr int AppVersion = 1001023; -constexpr str_const AppVersionStr = "1.1.23"; +constexpr str_const AppVersionStr = "1.1.23-procxx"; constexpr bool AppAlphaVersion = false; -constexpr uint64 AppBetaVersion = BETA_VERSION_MACRO; +constexpr uint64_t AppBetaVersion = BETA_VERSION_MACRO; diff --git a/Telegram/SourceFiles/dialogs/dialogs_indexed_list.h b/Telegram/SourceFiles/dialogs/dialogs_indexed_list.h index f4d95f24c..e439eaf75 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_indexed_list.h +++ b/Telegram/SourceFiles/dialogs/dialogs_indexed_list.h @@ -63,7 +63,7 @@ public: bool isEmpty() const { return all().isEmpty(); } bool contains(PeerId peerId) const { return all().contains(peerId); } Row *getRow(PeerId peerId) const { return all().getRow(peerId); } - Row *rowAtY(int32 y, int32 h) const { return all().rowAtY(y, h); } + Row *rowAtY(int32_t y, int32_t h) const { return all().rowAtY(y, h); } using iterator = List::iterator; using const_iterator = List::const_iterator; diff --git a/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp b/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp index 284037d78..1224b1d89 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp +++ b/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp @@ -812,7 +812,7 @@ void DialogsInner::step_pinnedShifting(TimeMs ms, bool timer) { if (updateMin < 0) updateMin = i; updateMax = i; if (start + st::stickersRowDuration > ms && ms >= start) { - _pinnedRows[i].yadd.update(float64(ms - start) / st::stickersRowDuration, anim::sineInOut); + _pinnedRows[i].yadd.update(double(ms - start) / st::stickersRowDuration, anim::sineInOut); animating = true; } else { _pinnedRows[i].yadd.finish(); @@ -1074,7 +1074,7 @@ void DialogsInner::dlgUpdated(Dialogs::Mode list, Dialogs::Row *row) { } } else if (_state == FilteredState || _state == SearchedState) { if (list == Dialogs::Mode::All) { - for (int32 i = 0, l = _filterResults.size(); i < l; ++i) { + for (int32_t i = 0, l = _filterResults.size(); i < l; ++i) { if (_filterResults.at(i)->history() == row->history()) { update(0, filteredOffset() + i * st::dialogsRowHeight, getFullWidth(), st::dialogsRowHeight); break; @@ -1163,7 +1163,7 @@ void DialogsInner::updateSelectedRow(PeerData *peer) { } } else if (_state == FilteredState || _state == SearchedState) { if (peer) { - for (int32 i = 0, l = _filterResults.size(); i != l; ++i) { + for (int32_t i = 0, l = _filterResults.size(); i != l; ++i) { if (_filterResults.at(i)->history()->peer == peer) { update(0, filteredOffset() + i * st::dialogsRowHeight, getFullWidth(), st::dialogsRowHeight); break; @@ -1515,7 +1515,7 @@ void DialogsInner::addAllSavedPeers() { addSavedPeersAfter(QDateTime()); } -bool DialogsInner::searchReceived(const QVector &messages, DialogsSearchRequestType type, int32 fullCount) { +bool DialogsInner::searchReceived(const QVector &messages, DialogsSearchRequestType type, int32_t fullCount) { if (type == DialogsSearchFromStart || type == DialogsSearchPeerFromStart) { clearSearchResults(false); } @@ -1669,7 +1669,7 @@ void DialogsInner::notify_historyMuteUpdated(History *history) { } void DialogsInner::refresh(bool toTop) { - int32 h = 0; + int32_t h = 0; if (_state == DefaultState) { if (shownDialogs()->isEmpty()) { h = st::noContactsHeight; @@ -1773,7 +1773,7 @@ void DialogsInner::clearFilter() { } } -void DialogsInner::selectSkip(int32 direction) { +void DialogsInner::selectSkip(int32_t direction) { if (_state == DefaultState) { if (_importantSwitchSelected) { if (!shownDialogs()->isEmpty() && direction > 0) { @@ -1824,7 +1824,7 @@ void DialogsInner::selectSkip(int32 direction) { _hashtagSelected = 0; } } else { - int32 cur = (_hashtagSelected >= 0 && _hashtagSelected < _hashtagResults.size()) ? _hashtagSelected : ((_filteredSelected >= 0 && _filteredSelected < _filterResults.size()) ? (_hashtagResults.size() + _filteredSelected) : ((_peerSearchSelected >= 0 && _peerSearchSelected < _peerSearchResults.size()) ? (_peerSearchSelected + _filterResults.size() + _hashtagResults.size()) : (_searchedSelected + _peerSearchResults.size() + _filterResults.size() + _hashtagResults.size()))); + int32_t cur = (_hashtagSelected >= 0 && _hashtagSelected < _hashtagResults.size()) ? _hashtagSelected : ((_filteredSelected >= 0 && _filteredSelected < _filterResults.size()) ? (_hashtagResults.size() + _filteredSelected) : ((_peerSearchSelected >= 0 && _peerSearchSelected < _peerSearchResults.size()) ? (_peerSearchSelected + _filterResults.size() + _hashtagResults.size()) : (_searchedSelected + _peerSearchResults.size() + _filterResults.size() + _hashtagResults.size()))); cur = snap(cur + direction, 0, static_cast(_hashtagResults.size() + _filterResults.size() + _peerSearchResults.size() + _searchResults.size()) - 1); if (cur < _hashtagResults.size()) { _hashtagSelected = cur; @@ -1854,14 +1854,14 @@ void DialogsInner::selectSkip(int32 direction) { } void DialogsInner::scrollToPeer(const PeerId &peer, MsgId msgId) { - int32 fromY = -1; + int32_t fromY = -1; if (_state == DefaultState) { if (auto row = shownDialogs()->getRow(peer)) { fromY = dialogsOffset() + row->pos() * st::dialogsRowHeight; } } else if (_state == FilteredState || _state == SearchedState) { if (msgId) { - for (int32 i = 0, c = _searchResults.size(); i < c; ++i) { + for (int32_t i = 0, c = _searchResults.size(); i < c; ++i) { if (_searchResults[i]->item()->history()->peer->id == peer && _searchResults[i]->item()->id == msgId) { fromY = searchedOffset() + i * st::dialogsRowHeight; break; @@ -1869,7 +1869,7 @@ void DialogsInner::scrollToPeer(const PeerId &peer, MsgId msgId) { } } if (fromY < 0) { - for (int32 i = 0, c = _filterResults.size(); i < c; ++i) { + for (int32_t i = 0, c = _filterResults.size(); i < c; ++i) { if (_filterResults[i]->history()->peer->id == peer) { fromY = filteredOffset() + (i * st::dialogsRowHeight); break; @@ -1882,7 +1882,7 @@ void DialogsInner::scrollToPeer(const PeerId &peer, MsgId msgId) { } } -void DialogsInner::selectSkipPage(int32 pixels, int32 direction) { +void DialogsInner::selectSkipPage(int32_t pixels, int32_t direction) { int toSkip = pixels / int(st::dialogsRowHeight); if (_state == DefaultState) { if (!_selected) { @@ -1937,10 +1937,10 @@ void DialogsInner::loadPeerPhotos() { } yTo -= otherStart; } else if (_state == FilteredState || _state == SearchedState) { - int32 from = (yFrom - filteredOffset()) / st::dialogsRowHeight; + int32_t from = (yFrom - filteredOffset()) / st::dialogsRowHeight; if (from < 0) from = 0; if (from < _filterResults.size()) { - int32 to = (yTo / int32(st::dialogsRowHeight)) + 1, w = width(); + int32_t to = (yTo / int32_t(st::dialogsRowHeight)) + 1, w = width(); if (to > _filterResults.size()) to = _filterResults.size(); for (; from < to; ++from) { @@ -1948,20 +1948,20 @@ void DialogsInner::loadPeerPhotos() { } } - from = (yFrom > filteredOffset() + st::searchedBarHeight ? ((yFrom - filteredOffset() - st::searchedBarHeight) / int32(st::dialogsRowHeight)) : 0) - _filterResults.size(); + from = (yFrom > filteredOffset() + st::searchedBarHeight ? ((yFrom - filteredOffset() - st::searchedBarHeight) / int32_t(st::dialogsRowHeight)) : 0) - _filterResults.size(); if (from < 0) from = 0; if (from < _peerSearchResults.size()) { - int32 to = (yTo > filteredOffset() + st::searchedBarHeight ? ((yTo - filteredOffset() - st::searchedBarHeight) / int32(st::dialogsRowHeight)) : 0) - _filterResults.size() + 1, w = width(); + int32_t to = (yTo > filteredOffset() + st::searchedBarHeight ? ((yTo - filteredOffset() - st::searchedBarHeight) / int32_t(st::dialogsRowHeight)) : 0) - _filterResults.size() + 1, w = width(); if (to > _peerSearchResults.size()) to = _peerSearchResults.size(); for (; from < to; ++from) { _peerSearchResults[from]->peer->loadUserpic(); } } - from = (yFrom > filteredOffset() + ((_peerSearchResults.empty() ? 0 : st::searchedBarHeight) + st::searchedBarHeight) ? ((yFrom - filteredOffset() - (_peerSearchResults.empty() ? 0 : st::searchedBarHeight) - st::searchedBarHeight) / int32(st::dialogsRowHeight)) : 0) - _filterResults.size() - _peerSearchResults.size(); + from = (yFrom > filteredOffset() + ((_peerSearchResults.empty() ? 0 : st::searchedBarHeight) + st::searchedBarHeight) ? ((yFrom - filteredOffset() - (_peerSearchResults.empty() ? 0 : st::searchedBarHeight) - st::searchedBarHeight) / int32_t(st::dialogsRowHeight)) : 0) - _filterResults.size() - _peerSearchResults.size(); if (from < 0) from = 0; if (from < _searchResults.size()) { - int32 to = (yTo > filteredOffset() + (_peerSearchResults.empty() ? 0 : st::searchedBarHeight) + st::searchedBarHeight ? ((yTo - filteredOffset() - (_peerSearchResults.empty() ? 0 : st::searchedBarHeight) - st::searchedBarHeight) / int32(st::dialogsRowHeight)) : 0) - _filterResults.size() - _peerSearchResults.size() + 1, w = width(); + int32_t to = (yTo > filteredOffset() + (_peerSearchResults.empty() ? 0 : st::searchedBarHeight) + st::searchedBarHeight ? ((yTo - filteredOffset() - (_peerSearchResults.empty() ? 0 : st::searchedBarHeight) - st::searchedBarHeight) / int32_t(st::dialogsRowHeight)) : 0) - _filterResults.size() - _peerSearchResults.size() + 1, w = width(); if (to > _searchResults.size()) to = _searchResults.size(); for (; from < to; ++from) { @@ -2043,7 +2043,7 @@ void DialogsInner::saveRecentHashtags(const QString &text) { auto found = false; QRegularExpressionMatch m; auto recent = cRecentSearchHashtags(); - for (int32 i = 0, next = 0; (m = TextUtilities::RegExpHashtag().match(text, i)).hasMatch(); i = next) { + for (int32_t i = 0, next = 0; (m = TextUtilities::RegExpHashtag().match(text, i)).hasMatch(); i = next) { i = m.capturedStart(); next = m.capturedEnd(); if (m.hasMatch()) { @@ -2233,7 +2233,7 @@ Dialogs::IndexedList *DialogsInner::contactsNoDialogsList() { return _contactsNoDialogs.get(); } -int32 DialogsInner::lastSearchDate() const { +int32_t DialogsInner::lastSearchDate() const { return _lastSearchDate; } diff --git a/Telegram/SourceFiles/dialogs/dialogs_inner_widget.h b/Telegram/SourceFiles/dialogs/dialogs_inner_widget.h index 31daf10c5..e60f59e53 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_inner_widget.h +++ b/Telegram/SourceFiles/dialogs/dialogs_inner_widget.h @@ -48,16 +48,16 @@ public: void dialogsReceived(const QVector &dialogs); void addSavedPeersAfter(const QDateTime &date); void addAllSavedPeers(); - bool searchReceived(const QVector &result, DialogsSearchRequestType type, int32 fullCount); + bool searchReceived(const QVector &result, DialogsSearchRequestType type, int32_t fullCount); void peerSearchReceived(const QString &query, const QVector &result); - void showMore(int32 pixels); + void showMore(int32_t pixels); void activate(); void contactsReceived(const QVector &result); - void selectSkip(int32 direction); - void selectSkipPage(int32 pixels, int32 direction); + void selectSkip(int32_t direction); + void selectSkipPage(int32_t pixels, int32_t direction); void createDialog(History *history); void dlgUpdated(Dialogs::Mode list, Dialogs::Row *row); @@ -81,7 +81,7 @@ public: Dialogs::IndexedList *contactsList(); Dialogs::IndexedList *dialogsList(); Dialogs::IndexedList *contactsNoDialogsList(); - int32 lastSearchDate() const; + int32_t lastSearchDate() const; PeerData *lastSearchPeer() const; MsgId lastSearchId() const; MsgId lastSearchMigratedId() const; diff --git a/Telegram/SourceFiles/dialogs/dialogs_layout.cpp b/Telegram/SourceFiles/dialogs/dialogs_layout.cpp index 1cf137a9c..f42dd4104 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_layout.cpp +++ b/Telegram/SourceFiles/dialogs/dialogs_layout.cpp @@ -50,7 +50,7 @@ void paintRowDate(Painter &p, const QDateTime &date, QRect &rectForName, bool ac } else { dt = lastDate.toString(qsl("d.MM.yy")); } - int32 dtWidth = st::dialogsDateFont->width(dt); + int32_t dtWidth = st::dialogsDateFont->width(dt); rectForName.setWidth(rectForName.width() - dtWidth - st::dialogsDateSkip); p.setFont(st::dialogsDateFont); p.setPen(active ? st::dialogsDateFgActive : (selected ? st::dialogsDateFgOver : st::dialogsDateFg)); @@ -419,7 +419,7 @@ void paintImportantSwitch(Painter &p, Mode current, int fullWidth, bool selected p.drawText(st::dialogsPadding.x(), textBaseline, text); if (mutedHidden) { - if (int32 unread = App::histories().unreadMutedCount()) { + if (int32_t unread = App::histories().unreadMutedCount()) { int unreadRight = fullWidth - st::dialogsPadding.x(); UnreadBadgeStyle st; st.muted = true; diff --git a/Telegram/SourceFiles/dialogs/dialogs_list.cpp b/Telegram/SourceFiles/dialogs/dialogs_list.cpp index 6731af0db..03e33ae1a 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_list.cpp +++ b/Telegram/SourceFiles/dialogs/dialogs_list.cpp @@ -34,10 +34,10 @@ List::List(SortMode sortMode) , _current(_last.get()) { } -void List::adjustCurrent(int32 y, int32 h) const { +void List::adjustCurrent(int32_t y, int32_t h) const { if (isEmpty()) return; - int32 pos = (y > 0) ? (y / h) : 0; + int32_t pos = (y > 0) ? (y / h) : 0; while (_current->_pos > pos && _current != _begin) { _current = _current->_prev; } diff --git a/Telegram/SourceFiles/dialogs/dialogs_list.h b/Telegram/SourceFiles/dialogs/dialogs_list.h index ccf4e1a55..ac40737f9 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_list.h +++ b/Telegram/SourceFiles/dialogs/dialogs_list.h @@ -43,7 +43,7 @@ public: Row *getRow(PeerId peerId) const { return _rowByPeer.value(peerId); } - Row *rowAtY(int32 y, int32 h) const { + Row *rowAtY(int32_t y, int32_t h) const { auto i = cfind(y, h); if (i == cend() || (*i)->pos() != ((y > 0) ? (y / h) : 0)) { return nullptr; diff --git a/Telegram/SourceFiles/dialogs/dialogs_search_from_controllers.cpp b/Telegram/SourceFiles/dialogs/dialogs_search_from_controllers.cpp index 43d0e38d1..d965cd3e8 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_search_from_controllers.cpp +++ b/Telegram/SourceFiles/dialogs/dialogs_search_from_controllers.cpp @@ -76,7 +76,7 @@ void ChatSearchFromController::rebuildRows() { auto wasEmpty = !delegate()->peerListFullRowsCount(); auto now = unixtime(); - QMultiMap ordered; + QMultiMap ordered; if (_chat->noParticipantInfo()) { Auth().api().requestFullPeer(_chat); } else if (!_chat->participants.isEmpty()) { diff --git a/Telegram/SourceFiles/dialogs/dialogs_widget.cpp b/Telegram/SourceFiles/dialogs/dialogs_widget.cpp index 641d59d9e..50ce05722 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_widget.cpp +++ b/Telegram/SourceFiles/dialogs/dialogs_widget.cpp @@ -29,7 +29,6 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "mainwindow.h" #include "mainwidget.h" #include "ui/widgets/input_fields.h" -#include "autoupdater.h" #include "auth_session.h" #include "messenger.h" #include "ui/effects/widget_fade_wrap.h" @@ -118,13 +117,6 @@ DialogsWidget::DialogsWidget(QWidget *parent, not_null cont connect(_filter, SIGNAL(changed()), this, SLOT(onFilterUpdate())); connect(_filter, SIGNAL(cursorPositionChanged(int,int)), this, SLOT(onFilterCursorMoved(int,int))); -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - Sandbox::connect(SIGNAL(updateLatest()), this, SLOT(onCheckUpdateStatus())); - Sandbox::connect(SIGNAL(updateFailed()), this, SLOT(onCheckUpdateStatus())); - Sandbox::connect(SIGNAL(updateReady()), this, SLOT(onCheckUpdateStatus())); - onCheckUpdateStatus(); -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - subscribe(Adaptive::Changed(), [this] { updateForwardBar(); }); _cancelSearch->setClickedCallback([this] { onCancelSearch(); }); @@ -162,24 +154,6 @@ DialogsWidget::DialogsWidget(QWidget *parent, not_null cont updateSearchFromVisibility(true); } -#ifndef TDESKTOP_DISABLE_AUTOUPDATE -void DialogsWidget::onCheckUpdateStatus() { - if (Sandbox::updatingState() == Application::UpdatingReady) { - if (_updateTelegram) return; - _updateTelegram.create(this); - _updateTelegram->show(); - _updateTelegram->setClickedCallback([] { - checkReadyUpdate(); - App::restart(); - }); - } else { - if (!_updateTelegram) return; - _updateTelegram.destroy(); - } - updateControlsGeometry(); -} -#endif // TDESKTOP_DISABLE_AUTOUPDATE - void DialogsWidget::activate() { _filter->setFocus(); _inner->activate(); @@ -462,7 +436,7 @@ void DialogsWidget::onDraggingScrollDelta(int delta) { } void DialogsWidget::onDraggingScrollTimer() { - auto delta = (_draggingScrollDelta > 0) ? qMin(_draggingScrollDelta * 3 / 20 + 1, int32(MaxScrollSpeed)) : qMax(_draggingScrollDelta * 3 / 20 - 1, -int32(MaxScrollSpeed)); + auto delta = (_draggingScrollDelta > 0) ? qMin(_draggingScrollDelta * 3 / 20 + 1, int32_t(MaxScrollSpeed)) : qMax(_draggingScrollDelta * 3 / 20 - 1, -int32_t(MaxScrollSpeed)); _scroll->scrollToY(_scroll->scrollTop() + delta); } @@ -966,7 +940,7 @@ void DialogsWidget::updateControlsGeometry() { filterAreaTop += st::dialogsForwardHeight; } auto smallLayoutWidth = (st::dialogsPadding.x() + st::dialogsPhotoSize + st::dialogsPadding.x()); - auto smallLayoutRatio = (width() < st::dialogsWidthMin) ? (st::dialogsWidthMin - width()) / float64(st::dialogsWidthMin - smallLayoutWidth) : 0.; + auto smallLayoutRatio = (width() < st::dialogsWidthMin) ? (st::dialogsWidthMin - width()) / double(st::dialogsWidthMin - smallLayoutWidth) : 0.; auto filterLeft = st::dialogsFilterPadding.x() + _mainMenuToggle->width() + st::dialogsFilterPadding.x(); auto filterRight = (Global::LocalPasscode() ? (st::dialogsFilterPadding.x() + _lockUnlock->width()) : st::dialogsFilterSkip) + st::dialogsFilterPadding.x(); auto filterWidth = qMax(width(), st::dialogsWidthMin) - filterLeft - filterRight; @@ -1174,7 +1148,7 @@ void DialogsWidget::onCancelSearchInPeer() { } void DialogsWidget::onDialogMoved(int movedFrom, int movedTo) { - int32 st = _scroll->scrollTop(); + int32_t st = _scroll->scrollTop(); if (st > movedTo && st < movedFrom) { _scroll->scrollToY(st + st::dialogsRowHeight); } diff --git a/Telegram/SourceFiles/dialogs/dialogs_widget.h b/Telegram/SourceFiles/dialogs/dialogs_widget.h index 1f0b27a91..34f54f020 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_widget.h +++ b/Telegram/SourceFiles/dialogs/dialogs_widget.h @@ -129,10 +129,6 @@ public slots: private slots: void onDraggingScrollTimer(); -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - void onCheckUpdateStatus(); -#endif // TDESKTOP_DISABLE_AUTOUPDATE - protected: void dragEnterEvent(QDragEnterEvent *e) override; void dragMoveEvent(QDragMoveEvent *e) override; @@ -171,7 +167,7 @@ private: QTimer _chooseByDragTimer; bool _dialogsFull = false; - int32 _dialogsOffsetDate = 0; + int32_t _dialogsOffsetDate = 0; MsgId _dialogsOffsetId = 0; PeerData *_dialogsOffsetPeer = nullptr; mtpRequestId _dialogsRequestId = 0; diff --git a/Telegram/SourceFiles/facades.cpp b/Telegram/SourceFiles/facades.cpp index 25a4c4a86..663e67972 100644 --- a/Telegram/SourceFiles/facades.cpp +++ b/Telegram/SourceFiles/facades.cpp @@ -249,7 +249,7 @@ void repaintHistoryItem(not_null item) { void autoplayMediaInlineAsync(const FullMsgId &msgId) { if (auto main = App::main()) { - QMetaObject::invokeMethod(main, "ui_autoplayMediaInlineAsync", Qt::QueuedConnection, Q_ARG(qint32, msgId.channel), Q_ARG(qint32, msgId.msg)); + QMetaObject::invokeMethod(main, "ui_autoplayMediaInlineAsync", Qt::QueuedConnection, Q_ARG(int32_t, msgId.channel), Q_ARG(int32_t, msgId.msg)); } } @@ -272,7 +272,7 @@ void showPeerHistory(const PeerId &peer, MsgId msgId, ShowWay way) { void showPeerHistoryAsync(const PeerId &peer, MsgId msgId, ShowWay way) { if (MainWidget *m = App::main()) { qRegisterMetaType(); - QMetaObject::invokeMethod(m, "ui_showPeerHistoryAsync", Qt::QueuedConnection, Q_ARG(quint64, peer), Q_ARG(qint32, msgId), Q_ARG(Ui::ShowWay, way)); + QMetaObject::invokeMethod(m, "ui_showPeerHistoryAsync", Qt::QueuedConnection, Q_ARG(uint64_t, peer), Q_ARG(int32_t, msgId), Q_ARG(Ui::ShowWay, way)); } } @@ -398,7 +398,7 @@ struct Data { } // namespace Sandbox std::unique_ptr SandboxData; -uint64 SandboxUserTag = 0; +uint64_t SandboxUserTag = 0; namespace Sandbox { @@ -413,7 +413,7 @@ bool CheckBetaVersionDir() { if (beta.open(QIODevice::WriteOnly)) { QDataStream dataStream(&beta); dataStream.setVersion(QDataStream::Qt_5_3); - dataStream << quint64(cRealBetaVersion()) << cBetaPrivateKey(); + dataStream << uint64_t(cRealBetaVersion()) << cBetaPrivateKey(); } else { LOG(("FATAL: Could not open '%1' for writing private key!").arg(beta.fileName())); return false; @@ -424,7 +424,7 @@ bool CheckBetaVersionDir() { QDataStream dataStream(&beta); dataStream.setVersion(QDataStream::Qt_5_3); - quint64 v; + uint64_t v; QByteArray k; dataStream >> v >> k; if (dataStream.status() == QDataStream::Ok) { @@ -461,12 +461,12 @@ void WorkingDirReady() { } } - srand((int32)time(NULL)); + srand((int32_t)time(NULL)); SandboxUserTag = 0; QFile usertag(cWorkingDir() + qsl("tdata/usertag")); if (usertag.open(QIODevice::ReadOnly)) { - if (usertag.read(reinterpret_cast(&SandboxUserTag), sizeof(uint64)) != sizeof(uint64)) { + if (usertag.read(reinterpret_cast(&SandboxUserTag), sizeof(uint64_t)) != sizeof(uint64_t)) { SandboxUserTag = 0; } usertag.close(); @@ -477,7 +477,7 @@ void WorkingDirReady() { } while (!SandboxUserTag); if (usertag.open(QIODevice::WriteOnly)) { - usertag.write(reinterpret_cast(&SandboxUserTag), sizeof(uint64)); + usertag.write(reinterpret_cast(&SandboxUserTag), sizeof(uint64_t)); usertag.close(); } } @@ -509,7 +509,7 @@ void finish() { MainThreadTaskHandler.destroy(); } -uint64 UserTag() { +uint64_t UserTag() { return SandboxUserTag; } @@ -538,38 +538,38 @@ struct Data { bool ScreenIsLocked = false; - int32 DebugLoggingFlags = 0; + int32_t DebugLoggingFlags = 0; - float64 RememberedSongVolume = kDefaultVolume; - float64 SongVolume = kDefaultVolume; + double RememberedSongVolume = kDefaultVolume; + double SongVolume = kDefaultVolume; base::Observable SongVolumeChanged; - float64 VideoVolume = kDefaultVolume; + double VideoVolume = kDefaultVolume; base::Observable VideoVolumeChanged; // config - int32 ChatSizeMax = 200; - int32 MegagroupSizeMax = 10000; - int32 ForwardedCountMax = 100; - int32 OnlineUpdatePeriod = 120000; - int32 OfflineBlurTimeout = 5000; - int32 OfflineIdleTimeout = 30000; - int32 OnlineFocusTimeout = 1000; - int32 OnlineCloudTimeout = 300000; - int32 NotifyCloudDelay = 30000; - int32 NotifyDefaultDelay = 1500; - int32 ChatBigSize = 10; - int32 PushChatPeriod = 60000; - int32 PushChatLimit = 2; - int32 SavedGifsLimit = 200; - int32 EditTimeLimit = 172800; - int32 StickersRecentLimit = 30; - int32 StickersFavedLimit = 5; - int32 PinnedDialogsCountMax = 5; + int32_t ChatSizeMax = 200; + int32_t MegagroupSizeMax = 10000; + int32_t ForwardedCountMax = 100; + int32_t OnlineUpdatePeriod = 120000; + int32_t OfflineBlurTimeout = 5000; + int32_t OfflineIdleTimeout = 30000; + int32_t OnlineFocusTimeout = 1000; + int32_t OnlineCloudTimeout = 300000; + int32_t NotifyCloudDelay = 30000; + int32_t NotifyDefaultDelay = 1500; + int32_t ChatBigSize = 10; + int32_t PushChatPeriod = 60000; + int32_t PushChatLimit = 2; + int32_t SavedGifsLimit = 200; + int32_t EditTimeLimit = 172800; + int32_t StickersRecentLimit = 30; + int32_t StickersFavedLimit = 5; + int32_t PinnedDialogsCountMax = 5; QString InternalLinksDomain = qsl("https://t.me/"); - int32 CallReceiveTimeoutMs = 20000; - int32 CallRingTimeoutMs = 90000; - int32 CallConnectTimeoutMs = 30000; - int32 CallPacketTimeoutMs = 10000; + int32_t CallReceiveTimeoutMs = 20000; + int32_t CallRingTimeoutMs = 90000; + int32_t CallConnectTimeoutMs = 30000; + int32_t CallPacketTimeoutMs = 10000; bool PhoneCallsEnabled = true; base::Observable PhoneCallsEnabledChanged; @@ -661,38 +661,38 @@ DefineVar(Global, bool, ModerateModeEnabled); DefineVar(Global, bool, ScreenIsLocked); -DefineVar(Global, int32, DebugLoggingFlags); +DefineVar(Global, int32_t, DebugLoggingFlags); -DefineVar(Global, float64, RememberedSongVolume); -DefineVar(Global, float64, SongVolume); +DefineVar(Global, double, RememberedSongVolume); +DefineVar(Global, double, SongVolume); DefineRefVar(Global, base::Observable, SongVolumeChanged); -DefineVar(Global, float64, VideoVolume); +DefineVar(Global, double, VideoVolume); DefineRefVar(Global, base::Observable, VideoVolumeChanged); // config -DefineVar(Global, int32, ChatSizeMax); -DefineVar(Global, int32, MegagroupSizeMax); -DefineVar(Global, int32, ForwardedCountMax); -DefineVar(Global, int32, OnlineUpdatePeriod); -DefineVar(Global, int32, OfflineBlurTimeout); -DefineVar(Global, int32, OfflineIdleTimeout); -DefineVar(Global, int32, OnlineFocusTimeout); -DefineVar(Global, int32, OnlineCloudTimeout); -DefineVar(Global, int32, NotifyCloudDelay); -DefineVar(Global, int32, NotifyDefaultDelay); -DefineVar(Global, int32, ChatBigSize); -DefineVar(Global, int32, PushChatPeriod); -DefineVar(Global, int32, PushChatLimit); -DefineVar(Global, int32, SavedGifsLimit); -DefineVar(Global, int32, EditTimeLimit); -DefineVar(Global, int32, StickersRecentLimit); -DefineVar(Global, int32, StickersFavedLimit); -DefineVar(Global, int32, PinnedDialogsCountMax); +DefineVar(Global, int32_t, ChatSizeMax); +DefineVar(Global, int32_t, MegagroupSizeMax); +DefineVar(Global, int32_t, ForwardedCountMax); +DefineVar(Global, int32_t, OnlineUpdatePeriod); +DefineVar(Global, int32_t, OfflineBlurTimeout); +DefineVar(Global, int32_t, OfflineIdleTimeout); +DefineVar(Global, int32_t, OnlineFocusTimeout); +DefineVar(Global, int32_t, OnlineCloudTimeout); +DefineVar(Global, int32_t, NotifyCloudDelay); +DefineVar(Global, int32_t, NotifyDefaultDelay); +DefineVar(Global, int32_t, ChatBigSize); +DefineVar(Global, int32_t, PushChatPeriod); +DefineVar(Global, int32_t, PushChatLimit); +DefineVar(Global, int32_t, SavedGifsLimit); +DefineVar(Global, int32_t, EditTimeLimit); +DefineVar(Global, int32_t, StickersRecentLimit); +DefineVar(Global, int32_t, StickersFavedLimit); +DefineVar(Global, int32_t, PinnedDialogsCountMax); DefineVar(Global, QString, InternalLinksDomain); -DefineVar(Global, int32, CallReceiveTimeoutMs); -DefineVar(Global, int32, CallRingTimeoutMs); -DefineVar(Global, int32, CallConnectTimeoutMs); -DefineVar(Global, int32, CallPacketTimeoutMs); +DefineVar(Global, int32_t, CallReceiveTimeoutMs); +DefineVar(Global, int32_t, CallRingTimeoutMs); +DefineVar(Global, int32_t, CallConnectTimeoutMs); +DefineVar(Global, int32_t, CallPacketTimeoutMs); DefineVar(Global, bool, PhoneCallsEnabled); DefineRefVar(Global, base::Observable, PhoneCallsEnabledChanged); diff --git a/Telegram/SourceFiles/facades.h b/Telegram/SourceFiles/facades.h index 287dd7dba..580852ff0 100644 --- a/Telegram/SourceFiles/facades.h +++ b/Telegram/SourceFiles/facades.h @@ -211,7 +211,7 @@ void start(); bool started(); void finish(); -uint64 UserTag(); +uint64_t UserTag(); DeclareVar(QByteArray, LastCrashDump); DeclareVar(ProxyData, PreLaunchProxy); @@ -250,7 +250,7 @@ constexpr auto FeaturedSetId = 0xFFFFFFFFFFFFFFFBULL; // for emoji/stickers pane constexpr auto FavedSetId = 0xFFFFFFFFFFFFFFFAULL; // for cloud-stored faved stickers constexpr auto MegagroupSetId = 0xFFFFFFFFFFFFFFEFULL; // for setting up megagroup sticker set struct Set { - Set(uint64 id, uint64 access, const QString &title, const QString &shortName, int32 count, int32 hash, MTPDstickerSet::Flags flags) + Set(uint64_t id, uint64_t access, const QString &title, const QString &shortName, int32_t count, int32_t hash, MTPDstickerSet::Flags flags) : id(id) , access(access) , title(title) @@ -259,15 +259,15 @@ struct Set { , hash(hash) , flags(flags) { } - uint64 id, access; + uint64_t id, access; QString title, shortName; - int32 count, hash; + int32_t count, hash; MTPDstickerSet::Flags flags; StickerPack stickers; StickersByEmojiMap emoji; }; -using Sets = QMap; -using Order = QList; +using Sets = QMap; +using Order = QList; inline MTPInputStickerSet inputSetId(const Set &set) { if (set.id && set.access) { @@ -300,40 +300,40 @@ DeclareVar(bool, ModerateModeEnabled); DeclareVar(bool, ScreenIsLocked); -DeclareVar(int32, DebugLoggingFlags); +DeclareVar(int32_t, DebugLoggingFlags); -constexpr float64 kDefaultVolume = 0.9; +constexpr double kDefaultVolume = 0.9; -DeclareVar(float64, RememberedSongVolume); -DeclareVar(float64, SongVolume); +DeclareVar(double, RememberedSongVolume); +DeclareVar(double, SongVolume); DeclareRefVar(base::Observable, SongVolumeChanged); -DeclareVar(float64, VideoVolume); +DeclareVar(double, VideoVolume); DeclareRefVar(base::Observable, VideoVolumeChanged); // config -DeclareVar(int32, ChatSizeMax); -DeclareVar(int32, MegagroupSizeMax); -DeclareVar(int32, ForwardedCountMax); -DeclareVar(int32, OnlineUpdatePeriod); -DeclareVar(int32, OfflineBlurTimeout); -DeclareVar(int32, OfflineIdleTimeout); -DeclareVar(int32, OnlineFocusTimeout); // not from config -DeclareVar(int32, OnlineCloudTimeout); -DeclareVar(int32, NotifyCloudDelay); -DeclareVar(int32, NotifyDefaultDelay); -DeclareVar(int32, ChatBigSize); -DeclareVar(int32, PushChatPeriod); -DeclareVar(int32, PushChatLimit); -DeclareVar(int32, SavedGifsLimit); -DeclareVar(int32, EditTimeLimit); -DeclareVar(int32, StickersRecentLimit); -DeclareVar(int32, StickersFavedLimit); -DeclareVar(int32, PinnedDialogsCountMax); +DeclareVar(int32_t, ChatSizeMax); +DeclareVar(int32_t, MegagroupSizeMax); +DeclareVar(int32_t, ForwardedCountMax); +DeclareVar(int32_t, OnlineUpdatePeriod); +DeclareVar(int32_t, OfflineBlurTimeout); +DeclareVar(int32_t, OfflineIdleTimeout); +DeclareVar(int32_t, OnlineFocusTimeout); // not from config +DeclareVar(int32_t, OnlineCloudTimeout); +DeclareVar(int32_t, NotifyCloudDelay); +DeclareVar(int32_t, NotifyDefaultDelay); +DeclareVar(int32_t, ChatBigSize); +DeclareVar(int32_t, PushChatPeriod); +DeclareVar(int32_t, PushChatLimit); +DeclareVar(int32_t, SavedGifsLimit); +DeclareVar(int32_t, EditTimeLimit); +DeclareVar(int32_t, StickersRecentLimit); +DeclareVar(int32_t, StickersFavedLimit); +DeclareVar(int32_t, PinnedDialogsCountMax); DeclareVar(QString, InternalLinksDomain); -DeclareVar(int32, CallReceiveTimeoutMs); -DeclareVar(int32, CallRingTimeoutMs); -DeclareVar(int32, CallConnectTimeoutMs); -DeclareVar(int32, CallPacketTimeoutMs); +DeclareVar(int32_t, CallReceiveTimeoutMs); +DeclareVar(int32_t, CallRingTimeoutMs); +DeclareVar(int32_t, CallConnectTimeoutMs); +DeclareVar(int32_t, CallPacketTimeoutMs); DeclareVar(bool, PhoneCallsEnabled); DeclareRefVar(base::Observable, PhoneCallsEnabledChanged); @@ -354,7 +354,7 @@ DeclareRefVar(base::Observable, FeaturedStickerSetsUnreadCountChanged); DeclareVar(TimeMs, LastFeaturedStickersUpdate); DeclareVar(Stickers::Order, ArchivedStickerSetsOrder); -typedef QMap CircleMasksMap; +typedef QMap CircleMasksMap; DeclareRefVar(CircleMasksMap, CircleMasks); DeclareRefVar(base::Observable, SelfChanged); diff --git a/Telegram/SourceFiles/history/history.cpp b/Telegram/SourceFiles/history/history.cpp index 0867d6221..3052cf111 100644 --- a/Telegram/SourceFiles/history/history.cpp +++ b/Telegram/SourceFiles/history/history.cpp @@ -56,7 +56,7 @@ constexpr auto kNewBlockEachMessage = 50; auto GlobalPinnedIndex = 0; -HistoryItem *createUnsupportedMessage(History *history, MsgId msgId, MTPDmessage::Flags flags, MsgId replyTo, int32 viaBotId, QDateTime date, int32 from) { +HistoryItem *createUnsupportedMessage(History *history, MsgId msgId, MTPDmessage::Flags flags, MsgId replyTo, int32_t viaBotId, QDateTime date, int32_t from) { auto text = TextWithEntities { lng_message_unsupported(lt_link, qsl("https://desktop.telegram.org")) }; TextUtilities::ParseEntities(text, _historyTextNoMonoOptions.flags); text.entities.push_front(EntityInText(EntityInTextItalic, 0, text.text.size())); @@ -421,7 +421,7 @@ void ChannelHistory::getRangeDifference() { } } -void ChannelHistory::getRangeDifferenceNext(int32 pts) { +void ChannelHistory::getRangeDifferenceNext(int32_t pts) { if (!App::main() || _rangeDifferenceToId < _rangeDifferenceFromId) return; int limit = _rangeDifferenceToId + 1 - _rangeDifferenceFromId; @@ -598,7 +598,7 @@ not_null Histories::findOrInsert(const PeerId &peerId) { return i.value(); } -not_null Histories::findOrInsert(const PeerId &peerId, int32 unreadCount, int32 maxInboxRead, int32 maxOutboxRead) { +not_null Histories::findOrInsert(const PeerId &peerId, int32_t unreadCount, int32_t maxInboxRead, int32_t maxOutboxRead) { auto i = map.constFind(peerId); if (i == map.cend()) { auto history = peerIsChannel(peerId) ? static_cast(new ChannelHistory(peerId)) : (new History(peerId)); @@ -1443,7 +1443,7 @@ void History::addOlderSlice(const QVector &slice) { oldLoaded = true; } else if (loadedAtBottom()) { // add photos to overview and authors to lastAuthors bool channel = isChannel(); - int32 mask = 0; + int32_t mask = 0; QList> *lastAuthors = nullptr; OrderedSet> *markupSenders = nullptr; if (peer->isChat()) { @@ -1585,7 +1585,7 @@ void History::checkAddAllToOverview() { return; } - int32 mask = 0; + int32_t mask = 0; for_const (auto block, blocks) { for_const (auto item, block->items) { mask |= item->addToOverview(AddToOverviewBack); @@ -1660,7 +1660,7 @@ MsgId History::inboxRead(HistoryItem *wasRead) { return inboxRead(wasRead ? wasRead->id : 0); } -MsgId History::outboxRead(int32 upTo) { +MsgId History::outboxRead(int32_t upTo) { if (upTo < 0) return upTo; if (!upTo) upTo = msgIdForRead(); accumulate_max(outboxReadBefore, upTo + 1); @@ -1698,7 +1698,7 @@ void History::setUnreadCount(int newUnreadCount) { main->unreadCountChanged(this); } if (unreadBar) { - int32 count = _unreadCount; + int32_t count = _unreadCount; if (peer->migrateTo()) { if (History *h = App::historyLoaded(peer->migrateTo()->id)) { count += h->unreadCount(); @@ -1812,7 +1812,7 @@ void History::countScrollTopItem(int top) { } } -void History::getNextScrollTopItem(HistoryBlock *block, int32 i) { +void History::getNextScrollTopItem(HistoryBlock *block, int32_t i) { ++i; if (i > 0 && i < block->items.size()) { scrollTopItem = block->items[i]; @@ -1829,7 +1829,7 @@ void History::getNextScrollTopItem(HistoryBlock *block, int32 i) { void History::addUnreadBar() { if (unreadBar || !showFrom || showFrom->detached() || !unreadCount()) return; - int32 count = unreadCount(); + int32_t count = unreadCount(); if (peer->migrateTo()) { if (History *h = App::historyLoaded(peer->migrateTo()->id)) { count += h->unreadCount(); @@ -1845,7 +1845,7 @@ void History::destroyUnreadBar() { } } -HistoryItem *History::addNewInTheMiddle(HistoryItem *newItem, int32 blockIndex, int32 itemIndex) { +HistoryItem *History::addNewInTheMiddle(HistoryItem *newItem, int32_t blockIndex, int32_t itemIndex) { Expects(blockIndex >= 0); Expects(blockIndex < blocks.size()); Expects(itemIndex >= 0); @@ -1972,15 +1972,15 @@ void History::setNotLoadedAtBottom() { } namespace { - uint32 _dialogsPosToTopShift = 0x80000000UL; + uint32_t _dialogsPosToTopShift = 0x80000000UL; } -inline uint64 dialogPosFromDate(const QDateTime &date) { +inline uint64_t dialogPosFromDate(const QDateTime &date) { if (date.isNull()) return 0; - return (uint64(date.toTime_t()) << 32) | (++_dialogsPosToTopShift); + return (uint64_t(date.toTime_t()) << 32) | (++_dialogsPosToTopShift); } -inline uint64 pinnedDialogPos(int pinnedIndex) { +inline uint64_t pinnedDialogPos(int pinnedIndex) { return 0xFFFFFFFF00000000ULL + pinnedIndex; } @@ -2201,9 +2201,9 @@ void History::clearOnDestroy() { History::PositionInChatListChange History::adjustByPosInChatList(Dialogs::Mode list, Dialogs::IndexedList *indexed) { Assert(indexed != nullptr); Dialogs::Row *lnk = mainChatListLink(list); - int32 movedFrom = lnk->pos(); + int32_t movedFrom = lnk->pos(); indexed->adjustByPos(chatListLinks(list)); - int32 movedTo = lnk->pos(); + int32_t movedTo = lnk->pos(); return { movedFrom, movedTo }; } @@ -2277,7 +2277,7 @@ void History::setPinnedIndex(int pinnedIndex) { } } -void History::overviewSliceDone(int32 overviewIndex, const MTPmessages_Messages &result, bool onlyCounts) { +void History::overviewSliceDone(int32_t overviewIndex, const MTPmessages_Messages &result, bool onlyCounts) { const QVector *v = 0; switch (result.type()) { case mtpc_messages_messages: { diff --git a/Telegram/SourceFiles/history/history.h b/Telegram/SourceFiles/history/history.h index 24db52f0d..56f27ae0d 100644 --- a/Telegram/SourceFiles/history/history.h +++ b/Telegram/SourceFiles/history/history.h @@ -55,7 +55,7 @@ public: History *find(const PeerId &peerId); not_null findOrInsert(const PeerId &peerId); - not_null findOrInsert(const PeerId &peerId, int32 unreadCount, int32 maxInboxRead, int32 maxOutboxRead); + not_null findOrInsert(const PeerId &peerId, int32_t unreadCount, int32_t maxInboxRead, int32_t maxOutboxRead); void clear(); void remove(const PeerId &peer); @@ -71,13 +71,13 @@ public: return _unreadMuted; } bool unreadOnlyMuted() const; - void unreadIncrement(int32 count, bool muted) { + void unreadIncrement(int32_t count, bool muted) { _unreadFull += count; if (muted) { _unreadMuted += count; } } - void unreadMuteChanged(int32 count, bool muted) { + void unreadMuteChanged(int32_t count, bool muted) { if (muted) { _unreadMuted += count; } else { @@ -275,7 +275,7 @@ public: bool needUpdateInChatList() const; void updateChatListSortPosition(); void setChatsListDate(const QDateTime &date); - uint64 sortKeyInChatList() const { + uint64_t sortKeyInChatList() const { return _sortKeyInChatList; } struct PositionInChatListChange { @@ -342,7 +342,7 @@ public: setHasPendingResizedItems(); } - void paintDialog(Painter &p, int32 w, bool sel) const; + void paintDialog(Painter &p, int32_t w, bool sel) const; bool updateSendActionNeedsAnimating(TimeMs ms, bool force = false); void unregSendAction(UserData *from); bool updateSendActionNeedsAnimating(UserData *user, const MTPSendMessageAction &action); @@ -380,7 +380,7 @@ public: int width = 0; int height = 0; - int32 msgCount = 0; + int32_t msgCount = 0; MsgId inboxReadBefore = 1; MsgId outboxReadBefore = 1; HistoryItem *showFrom = nullptr; @@ -450,7 +450,7 @@ protected: // and scrollTopOffset remains the same // if we are at the bottom of the window scrollTopItem == nullptr and // scrollTopOffset is undefined - void getNextScrollTopItem(HistoryBlock *block, int32 i); + void getNextScrollTopItem(HistoryBlock *block, int32_t i); // helper method for countScrollState(int top) void countScrollTopItem(int top); @@ -467,13 +467,13 @@ public: mutable const HistoryItem *textCachedFor = nullptr; // cache mutable Text lastItemTextCache; - bool overviewCountLoaded(int32 overviewIndex) const { + bool overviewCountLoaded(int32_t overviewIndex) const { return _overviewCountData[overviewIndex] >= 0; } - bool overviewLoaded(int32 overviewIndex) const { + bool overviewLoaded(int32_t overviewIndex) const { return overviewCount(overviewIndex) == _overview[overviewIndex].size(); } - int overviewCount(int32 overviewIndex, int32 defaultValue = -1) const { + int overviewCount(int32_t overviewIndex, int32_t defaultValue = -1) const { auto result = _overviewCountData[overviewIndex]; auto loaded = _overview[overviewIndex].size(); if (result < 0) return defaultValue; @@ -485,14 +485,14 @@ public: } return result; } - const OrderedSet &overview(int32 overviewIndex) const { + const OrderedSet &overview(int32_t overviewIndex) const { return _overview[overviewIndex]; } - MsgId overviewMinId(int32 overviewIndex) const { + MsgId overviewMinId(int32_t overviewIndex) const { return _overview[overviewIndex].empty() ? 0 : *_overview[overviewIndex].begin(); } - void overviewSliceDone(int32 overviewIndex, const MTPmessages_Messages &result, bool onlyCounts = false); - bool overviewHasMsgId(int32 overviewIndex, MsgId msgId) const { + void overviewSliceDone(int32_t overviewIndex, const MTPmessages_Messages &result, bool onlyCounts = false); + bool overviewHasMsgId(int32_t overviewIndex, MsgId msgId) const { return _overview[overviewIndex].contains(msgId); } @@ -519,7 +519,7 @@ protected: HistoryItem *createItemGame(MsgId id, MTPDmessage::Flags flags, UserId viaBotId, MsgId replyTo, QDateTime date, UserId from, const QString &postAuthor, GameData *game, const MTPReplyMarkup &markup); HistoryItem *addNewItem(HistoryItem *adding, bool newMsg); - HistoryItem *addNewInTheMiddle(HistoryItem *newItem, int32 blockIndex, int32 itemIndex); + HistoryItem *addNewInTheMiddle(HistoryItem *newItem, int32_t blockIndex, int32_t itemIndex); // All this methods add a new item to the first or last block // depending on if we are in isBuildingFronBlock() state. @@ -571,10 +571,10 @@ private: Assert(it != chatListLinks(list).cend()); return it.value(); } - uint64 _sortKeyInChatList = 0; // like ((unixtime) << 32) | (incremented counter) + uint64_t _sortKeyInChatList = 0; // like ((unixtime) << 32) | (incremented counter) OrderedSet _overview[OverviewCount]; - int32 _overviewCountData[OverviewCount]; // -1 - not loaded, 0 - all loaded, > 0 - count, but not all loaded + int32_t _overviewCountData[OverviewCount]; // -1 - not loaded, 0 - all loaded, > 0 - count, but not all loaded // A pointer to the block that is currently being built. // We hold this pointer so we can destroy it while building @@ -614,7 +614,7 @@ public: void messageDetached(HistoryItem *msg); void getRangeDifference(); - void getRangeDifferenceNext(int32 pts); + void getRangeDifferenceNext(int32_t pts); HistoryJoined *insertJoinedMessage(bool unread); void checkJoinedMessage(bool createUnread = false); @@ -636,7 +636,7 @@ private: HistoryJoined *_joinedMessage = nullptr; MsgId _rangeDifferenceFromId, _rangeDifferenceToId; - int32 _rangeDifferencePts; + int32_t _rangeDifferencePts; mtpRequestId _rangeDifferenceRequestId; }; diff --git a/Telegram/SourceFiles/history/history_admin_log_inner.cpp b/Telegram/SourceFiles/history/history_admin_log_inner.cpp index 85bd2b2be..c5e3b80ee 100644 --- a/Telegram/SourceFiles/history/history_admin_log_inner.cpp +++ b/Telegram/SourceFiles/history/history_admin_log_inner.cpp @@ -1396,7 +1396,7 @@ void InnerWidget::performDrag() { // ) { // uponSelected = false; // } else { - // uint16 selFrom = _selected.cbegin().value().from, selTo = _selected.cbegin().value().to; + // uint16_t selFrom = _selected.cbegin().value().from, selTo = _selected.cbegin().value().to; // if (dragState.symbol < selFrom || dragState.symbol >= selTo) { // uponSelected = false; // } diff --git a/Telegram/SourceFiles/history/history_admin_log_inner.h b/Telegram/SourceFiles/history/history_admin_log_inner.h index b9a427c40..405fc068c 100644 --- a/Telegram/SourceFiles/history/history_admin_log_inner.h +++ b/Telegram/SourceFiles/history/history_admin_log_inner.h @@ -181,7 +181,7 @@ private: not_null _channel; not_null _history; std::vector _items; - std::map _itemsByIds; + std::map _itemsByIds; int _itemsTop = 0; int _itemsHeight = 0; @@ -200,8 +200,8 @@ private: int _scrollDateLastItemTop = 0; // Up - max, Down - min. - uint64 _maxId = 0; - uint64 _minId = 0; + uint64_t _maxId = 0; + uint64_t _minId = 0; mtpRequestId _preloadUpRequestId = 0; mtpRequestId _preloadDownRequestId = 0; @@ -217,7 +217,7 @@ private: QPoint _mousePosition; HistoryItem *_mouseActionItem = nullptr; HistoryCursorState _mouseCursorState = HistoryDefaultCursorState; - uint16 _mouseTextSymbol = 0; + uint16_t _mouseTextSymbol = 0; bool _pressWasInactive = false; HistoryItem *_selectedItem = nullptr; diff --git a/Telegram/SourceFiles/history/history_admin_log_item.cpp b/Telegram/SourceFiles/history/history_admin_log_item.cpp index 2586bc8f3..e222b5332 100644 --- a/Telegram/SourceFiles/history/history_admin_log_item.cpp +++ b/Telegram/SourceFiles/history/history_admin_log_item.cpp @@ -43,7 +43,7 @@ TextWithEntities PrepareText(const QString &value, const QString &emptyValue) { return result; } -MTPMessage PrepareLogMessage(const MTPMessage &message, MsgId newId, int32 newDate) { +MTPMessage PrepareLogMessage(const MTPMessage &message, MsgId newId, int32_t newDate) { switch (message.type()) { case mtpc_messageEmpty: return MTP_messageEmpty(MTP_int(newId)); case mtpc_messageService: { @@ -87,10 +87,10 @@ TextWithEntities ExtractEditedText(const MTPMessage &message) { return { text, entities }; } -PhotoData *GenerateChatPhoto(ChannelId channelId, uint64 logEntryId, MTPint date, const MTPDchatPhoto &photo) { +PhotoData *GenerateChatPhoto(ChannelId channelId, uint64_t logEntryId, MTPint date, const MTPDchatPhoto &photo) { // We try to make a unique photoId that will stay the same for each pair (channelId, logEntryId). - static const auto RandomIdPart = rand_value(); - auto mixinIdPart = (static_cast(static_cast(channelId)) << 32) ^ logEntryId; + static const auto RandomIdPart = rand_value(); + auto mixinIdPart = (static_cast(static_cast(channelId)) << 32) ^ logEntryId; auto photoId = RandomIdPart ^ mixinIdPart; auto photoSizes = QVector(); diff --git a/Telegram/SourceFiles/history/history_admin_log_section.h b/Telegram/SourceFiles/history/history_admin_log_section.h index 327f22a4f..7984f4be6 100644 --- a/Telegram/SourceFiles/history/history_admin_log_section.h +++ b/Telegram/SourceFiles/history/history_admin_log_section.h @@ -161,7 +161,7 @@ public: return std::move(_adminsCanEdit); } - void setItems(std::vector &&items, std::map &&itemsByIds, bool upLoaded, bool downLoaded) { + void setItems(std::vector &&items, std::map &&itemsByIds, bool upLoaded, bool downLoaded) { _items = std::move(items); _itemsByIds = std::move(itemsByIds); _upLoaded = upLoaded; @@ -179,7 +179,7 @@ public: std::vector takeItems() { return std::move(_items); } - std::map takeItemsByIds() { + std::map takeItemsByIds() { return std::move(_itemsByIds); } LocalIdManager takeIdManager() { @@ -204,7 +204,7 @@ private: std::vector> _admins; std::vector> _adminsCanEdit; std::vector _items; - std::map _itemsByIds; + std::map _itemsByIds; bool _upLoaded = false; bool _downLoaded = true; LocalIdManager _idManager; diff --git a/Telegram/SourceFiles/history/history_inner_widget.cpp b/Telegram/SourceFiles/history/history_inner_widget.cpp index f83b174db..bad864d52 100644 --- a/Telegram/SourceFiles/history/history_inner_widget.cpp +++ b/Telegram/SourceFiles/history/history_inner_widget.cpp @@ -149,7 +149,7 @@ void HistoryInner::messagesReceivedDown(PeerData *peer, const QVectordetached() || !_history) return; - int32 msgy = itemTop(item); + int32_t msgy = itemTop(item); if (msgy >= 0) { update(0, msgy, width(), item->height()); } @@ -435,7 +435,7 @@ void HistoryInner::paintEvent(QPaintEvent *e) { _widget->enqueueMessageHighlight(item); } - int32 h = item->height(); + int32_t h = item->height(); p.translate(0, h); y += h; @@ -587,7 +587,7 @@ void HistoryInner::onTouchScrollTimer() { _touchScrollState = Ui::TouchScrollState::Manual; touchResetSpeed(); } else if (_touchScrollState == Ui::TouchScrollState::Auto || _touchScrollState == Ui::TouchScrollState::Acceleration) { - int32 elapsed = int32(nowTime - _touchTime); + int32_t elapsed = int32_t(nowTime - _touchTime); QPoint delta = _touchSpeed * elapsed / 1000; bool hasScrolled = _widget->touchScroll(delta); @@ -646,9 +646,9 @@ void HistoryInner::touchResetSpeed() { _touchPrevPosValid = false; } -void HistoryInner::touchDeaccelerate(int32 elapsed) { - int32 x = _touchSpeed.x(); - int32 y = _touchSpeed.y(); +void HistoryInner::touchDeaccelerate(int32_t elapsed) { + int32_t x = _touchSpeed.x(); + int32_t y = _touchSpeed.y(); _touchSpeed.setX((x == 0) ? x : (x > 0) ? qMax(0, x - elapsed) : qMin(0, x + elapsed)); _touchSpeed.setY((y == 0) ? y : (y > 0) ? qMax(0, y - elapsed) : qMin(0, y + elapsed)); } @@ -777,7 +777,7 @@ void HistoryInner::touchScrollUpdated(const QPoint &screenPos) { } QPoint HistoryInner::mapPointToItem(QPoint p, HistoryItem *item) { - int32 msgy = itemTop(item); + int32_t msgy = itemTop(item); if (msgy < 0) return QPoint(0, 0); p.setY(p.y() - msgy); @@ -857,7 +857,7 @@ void HistoryInner::mouseActionStart(const QPoint &screenPos, Qt::MouseButton but ) { uponSelected = false; } else { - uint16 selFrom = _selected.cbegin().value().from, selTo = _selected.cbegin().value().to; + uint16_t selFrom = _selected.cbegin().value().from, selTo = _selected.cbegin().value().to; if (_mouseTextSymbol < selFrom || _mouseTextSymbol >= selTo) { uponSelected = false; } @@ -925,7 +925,7 @@ void HistoryInner::performDrag() { ) { uponSelected = false; } else { - uint16 selFrom = _selected.cbegin().value().from, selTo = _selected.cbegin().value().to; + uint16_t selFrom = _selected.cbegin().value().from, selTo = _selected.cbegin().value().to; if (dragState.symbol < selFrom || dragState.symbol >= selTo) { uponSelected = false; } @@ -1168,7 +1168,7 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) { isUponSelected = -2; } } else { - uint16 selFrom = _selected.cbegin().value().from, selTo = _selected.cbegin().value().to; + uint16_t selFrom = _selected.cbegin().value().from, selTo = _selected.cbegin().value().to; hasSelected = (selTo > selFrom) ? 1 : 0; if (App::mousedItem() && App::mousedItem() == App::hoveredItem()) { auto mousePos = mapPointToItem(mapFromGlobal(_mousePosition), App::mousedItem()); @@ -1609,22 +1609,22 @@ void HistoryInner::recountHeight() { updateBotInfo(false); if (_botAbout && !_botAbout->info->text.isEmpty()) { - int32 tw = _scroll->width() - st::msgMargin.left() - st::msgMargin.right(); + int32_t tw = _scroll->width() - st::msgMargin.left() - st::msgMargin.right(); if (tw > st::msgMaxWidth) tw = st::msgMaxWidth; tw -= st::msgPadding.left() + st::msgPadding.right(); - int32 mw = qMax(_botAbout->info->text.maxWidth(), st::msgNameFont->width(lang(lng_bot_description))); + int32_t mw = qMax(_botAbout->info->text.maxWidth(), st::msgNameFont->width(lang(lng_bot_description))); if (tw > mw) tw = mw; _botAbout->width = tw; _botAbout->height = _botAbout->info->text.countHeight(_botAbout->width); - int32 descH = st::msgMargin.top() + st::msgPadding.top() + st::msgNameFont->height + st::botDescSkip + _botAbout->height + st::msgPadding.bottom() + st::msgMargin.bottom(); - int32 descMaxWidth = _scroll->width(); + int32_t descH = st::msgMargin.top() + st::msgPadding.top() + st::msgNameFont->height + st::botDescSkip + _botAbout->height + st::msgPadding.bottom() + st::msgMargin.bottom(); + int32_t descMaxWidth = _scroll->width(); if (Adaptive::ChatWide()) { - descMaxWidth = qMin(descMaxWidth, int32(st::msgMaxWidth + 2 * st::msgPhotoSkip + 2 * st::msgMargin.left())); + descMaxWidth = qMin(descMaxWidth, int32_t(st::msgMaxWidth + 2 * st::msgPhotoSkip + 2 * st::msgMargin.left())); } - int32 descAtX = (descMaxWidth - _botAbout->width) / 2 - st::msgPadding.left(); - int32 descAtY = qMin(_historyPaddingTop - descH, qMax(0, (_scroll->height() - descH) / 2)) + st::msgMargin.top(); + int32_t descAtX = (descMaxWidth - _botAbout->width) / 2 - st::msgPadding.left(); + int32_t descAtY = qMin(_historyPaddingTop - descH, qMax(0, (_scroll->height() - descH) / 2)) + st::msgMargin.top(); _botAbout->rect = QRect(descAtX, descAtY, _botAbout->width + st::msgPadding.left() + st::msgPadding.right(), descH - st::msgMargin.top() - st::msgMargin.bottom()); } else if (_botAbout) { @@ -1653,10 +1653,10 @@ void HistoryInner::updateBotInfo(bool recount) { if (_botAbout->info->text.isEmpty()) { _botAbout->info->text.setText(st::messageTextStyle, _botAbout->info->description, _historyBotNoMonoOptions); if (recount) { - int32 tw = _scroll->width() - st::msgMargin.left() - st::msgMargin.right(); + int32_t tw = _scroll->width() - st::msgMargin.left() - st::msgMargin.right(); if (tw > st::msgMaxWidth) tw = st::msgMaxWidth; tw -= st::msgPadding.left() + st::msgPadding.right(); - int32 mw = qMax(_botAbout->info->text.maxWidth(), st::msgNameFont->width(lang(lng_bot_description))); + int32_t mw = qMax(_botAbout->info->text.maxWidth(), st::msgNameFont->width(lang(lng_bot_description))); if (tw > mw) tw = mw; _botAbout->width = tw; @@ -1672,9 +1672,9 @@ void HistoryInner::updateBotInfo(bool recount) { updateSize(); } if (_botAbout->height > 0) { - int32 descH = st::msgMargin.top() + st::msgPadding.top() + st::msgNameFont->height + st::botDescSkip + _botAbout->height + st::msgPadding.bottom() + st::msgMargin.bottom(); - int32 descAtX = (_scroll->width() - _botAbout->width) / 2 - st::msgPadding.left(); - int32 descAtY = qMin(_historyPaddingTop - descH, (_scroll->height() - descH) / 2) + st::msgMargin.top(); + int32_t descH = st::msgMargin.top() + st::msgPadding.top() + st::msgNameFont->height + st::botDescSkip + _botAbout->height + st::msgPadding.bottom() + st::msgMargin.bottom(); + int32_t descAtX = (_scroll->width() - _botAbout->width) / 2 - st::msgPadding.left(); + int32_t descAtY = qMin(_historyPaddingTop - descH, (_scroll->height() - descH) / 2) + st::msgMargin.top(); _botAbout->rect = QRect(descAtX, descAtY, _botAbout->width + st::msgPadding.left() + st::msgPadding.right(), descH - st::msgMargin.top() - st::msgMargin.bottom()); } else { @@ -1802,13 +1802,13 @@ void HistoryInner::updateSize() { } if (_botAbout && _botAbout->height > 0) { - int32 descH = st::msgMargin.top() + st::msgPadding.top() + st::msgNameFont->height + st::botDescSkip + _botAbout->height + st::msgPadding.bottom() + st::msgMargin.bottom(); - int32 descMaxWidth = _scroll->width(); + int32_t descH = st::msgMargin.top() + st::msgPadding.top() + st::msgNameFont->height + st::botDescSkip + _botAbout->height + st::msgPadding.bottom() + st::msgMargin.bottom(); + int32_t descMaxWidth = _scroll->width(); if (Adaptive::ChatWide()) { - descMaxWidth = qMin(descMaxWidth, int32(st::msgMaxWidth + 2 * st::msgPhotoSkip + 2 * st::msgMargin.left())); + descMaxWidth = qMin(descMaxWidth, int32_t(st::msgMaxWidth + 2 * st::msgPhotoSkip + 2 * st::msgMargin.left())); } - int32 descAtX = (descMaxWidth - _botAbout->width) / 2 - st::msgPadding.left(); - int32 descAtY = qMin(newHistoryPaddingTop - descH, qMax(0, (_scroll->height() - descH) / 2)) + st::msgMargin.top(); + int32_t descAtX = (descMaxWidth - _botAbout->width) / 2 - st::msgPadding.left(); + int32_t descAtY = qMin(newHistoryPaddingTop - descH, qMax(0, (_scroll->height() - descH) / 2)) + st::msgMargin.top(); _botAbout->rect = QRect(descAtX, descAtY, _botAbout->width + st::msgPadding.left() + st::msgPadding.right(), descH - st::msgMargin.top() - st::msgMargin.bottom()); } @@ -1858,8 +1858,8 @@ bool HistoryInner::focusNextPrevChild(bool next) { } } -void HistoryInner::adjustCurrent(int32 y) const { - int32 htop = historyTop(), hdrawtop = historyDrawTop(), mtop = migratedTop(); +void HistoryInner::adjustCurrent(int32_t y) const { + int32_t htop = historyTop(), hdrawtop = historyDrawTop(), mtop = migratedTop(); _curHistory = 0; if (mtop >= 0) { adjustCurrent(y - mtop, _migrated); @@ -1869,7 +1869,7 @@ void HistoryInner::adjustCurrent(int32 y) const { } } -void HistoryInner::adjustCurrent(int32 y, History *history) const { +void HistoryInner::adjustCurrent(int32_t y, History *history) const { Assert(!history->isEmpty()); _curHistory = history; if (_curBlock >= history->blocks.size()) { @@ -2082,7 +2082,7 @@ void HistoryInner::onUpdateSelected() { auto dateLeft = st::msgServiceMargin.left(); auto maxwidth = item->history()->width; if (Adaptive::ChatWide()) { - maxwidth = qMin(maxwidth, int32(st::msgMaxWidth + 2 * st::msgPhotoSkip + 2 * st::msgMargin.left())); + maxwidth = qMin(maxwidth, int32_t(st::msgMaxWidth + 2 * st::msgPhotoSkip + 2 * st::msgMargin.left())); } auto widthForDate = maxwidth - st::msgServiceMargin.left() - st::msgServiceMargin.left(); @@ -2155,7 +2155,7 @@ void HistoryInner::onUpdateSelected() { if (_mouseAction == MouseAction::Selecting) { auto canSelectMany = (_history != nullptr); if (selectingText) { - uint16 second = dragState.symbol; + uint16_t second = dragState.symbol; if (dragState.afterSymbol && _mouseSelectType == TextSelectType::Letters) { ++second; } @@ -2246,7 +2246,7 @@ void HistoryInner::updateDragSelection(HistoryItem *dragSelFrom, HistoryItem *dr if (_dragSelFrom != dragSelFrom || _dragSelTo != dragSelTo || _dragSelecting != dragSelecting) { _dragSelFrom = dragSelFrom; _dragSelTo = dragSelTo; - int32 fromy = itemTop(_dragSelFrom), toy = itemTop(_dragSelTo); + int32_t fromy = itemTop(_dragSelFrom), toy = itemTop(_dragSelTo); if (fromy >= 0 && toy >= 0 && fromy > toy) { qSwap(_dragSelFrom, _dragSelTo); } @@ -2350,11 +2350,11 @@ void HistoryInner::applyDragSelection() { applyDragSelection(&_selected); } -void HistoryInner::addSelectionRange(SelectedItems *toItems, int32 fromblock, int32 fromitem, int32 toblock, int32 toitem, History *h) const { +void HistoryInner::addSelectionRange(SelectedItems *toItems, int32_t fromblock, int32_t fromitem, int32_t toblock, int32_t toitem, History *h) const { if (fromblock >= 0 && fromitem >= 0 && toblock >= 0 && toitem >= 0) { for (; fromblock <= toblock; ++fromblock) { HistoryBlock *block = h->blocks[fromblock]; - for (int32 cnt = (fromblock < toblock) ? block->items.size() : (toitem + 1); fromitem < cnt; ++fromitem) { + for (int32_t cnt = (fromblock < toblock) ? block->items.size() : (toitem + 1); fromitem < cnt; ++fromitem) { HistoryItem *item = block->items[fromitem]; SelectedItems::iterator i = toItems->find(item); if (item->id > 0 && !item->serviceMsg()) { @@ -2377,7 +2377,7 @@ void HistoryInner::addSelectionRange(SelectedItems *toItems, int32 fromblock, in } void HistoryInner::applyDragSelection(SelectedItems *toItems) const { - int32 selfromy = itemTop(_dragSelFrom), seltoy = itemTop(_dragSelTo); + int32_t selfromy = itemTop(_dragSelFrom), seltoy = itemTop(_dragSelTo); if (selfromy < 0 || seltoy < 0) { return; } @@ -2387,8 +2387,8 @@ void HistoryInner::applyDragSelection(SelectedItems *toItems) const { toItems->clear(); } if (_dragSelecting) { - int32 fromblock = _dragSelFrom->block()->indexInHistory(), fromitem = _dragSelFrom->indexInBlock(); - int32 toblock = _dragSelTo->block()->indexInHistory(), toitem = _dragSelTo->indexInBlock(); + int32_t fromblock = _dragSelFrom->block()->indexInHistory(), fromitem = _dragSelFrom->indexInBlock(); + int32_t toblock = _dragSelTo->block()->indexInHistory(), toitem = _dragSelTo->indexInBlock(); if (_migrated) { if (_dragSelFrom->history() == _migrated) { if (_dragSelTo->history() == _migrated) { @@ -2408,7 +2408,7 @@ void HistoryInner::applyDragSelection(SelectedItems *toItems) const { addSelectionRange(toItems, fromblock, fromitem, toblock, toitem, _history); } else { for (SelectedItems::iterator i = toItems->begin(); i != toItems->cend();) { - int32 iy = itemTop(i.key()); + int32_t iy = itemTop(i.key()); if (iy < 0) { if (iy < -1) i = toItems->erase(i); continue; diff --git a/Telegram/SourceFiles/history/history_inner_widget.h b/Telegram/SourceFiles/history/history_inner_widget.h index 0836f4513..89f779a4a 100644 --- a/Telegram/SourceFiles/history/history_inner_widget.h +++ b/Telegram/SourceFiles/history/history_inner_widget.h @@ -150,10 +150,10 @@ private: void touchResetSpeed(); void touchUpdateSpeed(); - void touchDeaccelerate(int32 elapsed); + void touchDeaccelerate(int32_t elapsed); - void adjustCurrent(int32 y) const; - void adjustCurrent(int32 y, History *history) const; + void adjustCurrent(int32_t y) const; + void adjustCurrent(int32_t y, History *history) const; HistoryItem *prevItem(HistoryItem *item); HistoryItem *nextItem(HistoryItem *item); void updateDragSelection(HistoryItem *dragSelFrom, HistoryItem *dragSelTo, bool dragSelecting, bool force = false); @@ -210,7 +210,7 @@ private: SelectedItems _selected; void applyDragSelection(); void applyDragSelection(SelectedItems *toItems) const; - void addSelectionRange(SelectedItems *toItems, int32 fromblock, int32 fromitem, int32 toblock, int32 toitem, History *h) const; + void addSelectionRange(SelectedItems *toItems, int32_t fromblock, int32_t fromitem, int32_t toblock, int32_t toitem, History *h) const; // Does any of the shown histories has this flag set. bool hasPendingResizedItems() const { @@ -223,7 +223,7 @@ private: QPoint _mousePosition; HistoryItem *_mouseActionItem = nullptr; HistoryCursorState _mouseCursorState = HistoryDefaultCursorState; - uint16 _mouseTextSymbol = 0; + uint16_t _mouseTextSymbol = 0; bool _pressWasInactive = false; QPoint _trippleClickPoint; diff --git a/Telegram/SourceFiles/history/history_item.cpp b/Telegram/SourceFiles/history/history_item.cpp index 98d3de397..2da224e21 100644 --- a/Telegram/SourceFiles/history/history_item.cpp +++ b/Telegram/SourceFiles/history/history_item.cpp @@ -137,7 +137,7 @@ void ReplyKeyboard::resize(int width, int height) { _width = width; auto markup = _item->Get(); - float64 y = 0, buttonHeight = _rows.isEmpty() ? _st->buttonHeight() : (float64(height + _st->buttonSkip()) / _rows.size()); + double y = 0, buttonHeight = _rows.isEmpty() ? _st->buttonHeight() : (double(height + _st->buttonSkip()) / _rows.size()); for (auto &row : _rows) { int s = row.size(); @@ -154,20 +154,20 @@ void ReplyKeyboard::resize(int width, int height) { bool exact = (widthForText == widthOfText); bool enough = (widthForButtons - s * maxMinButtonWidth) >= widthOfText; - float64 x = 0; + double x = 0; for (Button &button : row) { int buttonw = qMax(button.text.maxWidth(), 1); - float64 textw = buttonw, minw = _st->minButtonWidth(button.type); - float64 w = textw; + double textw = buttonw, minw = _st->minButtonWidth(button.type); + double w = textw; if (exact) { w += minw; } else if (enough) { - w = (widthForButtons / float64(s)); + w = (widthForButtons / double(s)); textw = w - minw; } else { - textw = (widthForText / float64(s)); + textw = (widthForText / double(s)); w = minw + textw; - accumulate_max(w, 2 * float64(_st->buttonPadding())); + accumulate_max(w, 2 * double(_st->buttonPadding())); } int rectx = static_cast(std::floor(x)); @@ -328,7 +328,7 @@ void ReplyKeyboard::startAnimation(int i, int j, int direction) { void ReplyKeyboard::step_selected(TimeMs ms, bool timer) { for (Animations::iterator i = _animations.begin(); i != _animations.end();) { int index = qAbs(i.key()) - 1, row = (index / MatrixRowShift), col = index % MatrixRowShift; - float64 dt = float64(ms - i.value()) / st::botKbDuration; + double dt = double(ms - i.value()) / st::botKbDuration; if (dt >= 1) { _rows[row][col].howMuchOver = (i.key() > 0) ? 1 : 0; i = _animations.erase(i); @@ -525,7 +525,7 @@ void HistoryMessageUnreadBar::paint(Painter &p, int y, int w) const { int left = st::msgServiceMargin.left(); int maxwidth = w; if (Adaptive::ChatWide()) { - maxwidth = qMin(maxwidth, int32(st::msgMaxWidth + 2 * st::msgPhotoSkip + 2 * st::msgMargin.left())); + maxwidth = qMin(maxwidth, int32_t(st::msgMaxWidth + 2 * st::msgPhotoSkip + 2 * st::msgMargin.left())); } w = maxwidth; @@ -586,14 +586,14 @@ HistoryMediaPtr::~HistoryMediaPtr() { namespace internal { -TextSelection unshiftSelection(TextSelection selection, uint16 byLength) { +TextSelection unshiftSelection(TextSelection selection, uint16_t byLength) { if (selection == FullSelection) { return selection; } return ::unshiftSelection(selection, byLength); } -TextSelection shiftSelection(TextSelection selection, uint16 byLength) { +TextSelection shiftSelection(TextSelection selection, uint16_t byLength) { if (selection == FullSelection) { return selection; } diff --git a/Telegram/SourceFiles/history/history_item.h b/Telegram/SourceFiles/history/history_item.h index 5e3d6ef22..b35560f3d 100644 --- a/Telegram/SourceFiles/history/history_item.h +++ b/Telegram/SourceFiles/history/history_item.h @@ -84,7 +84,7 @@ struct HistoryTextState { HistoryCursorState cursor = HistoryDefaultCursorState; ClickHandlerPtr link; bool afterSymbol = false; - uint16 symbol = 0; + uint16_t symbol = 0; }; struct HistoryStateRequest { @@ -103,8 +103,8 @@ enum InfoDisplayType { }; struct HistoryMessageVia : public RuntimeComponent { - void create(int32 userId); - void resize(int32 availw) const; + void create(int32_t userId); + void resize(int32_t availw) const; UserData *_bot = nullptr; mutable QString _text; @@ -309,7 +309,7 @@ public: } protected: - virtual void paintButtonBg(Painter &p, const QRect &rect, float64 howMuchOver) const = 0; + virtual void paintButtonBg(Painter &p, const QRect &rect, double howMuchOver) const = 0; virtual void paintButtonIcon(Painter &p, const QRect &rect, int outerWidth, HistoryMessageReplyMarkup::Button::Type type) const = 0; virtual void paintButtonLoading(Painter &p, const QRect &rect) const = 0; virtual int minButtonWidth(HistoryMessageReplyMarkup::Button::Type type) const = 0; @@ -353,7 +353,7 @@ private: Text text = { 1 }; QRect rect; int characters = 0; - float64 howMuchOver = 0.; + double howMuchOver = 0.; HistoryMessageReplyMarkup::Button::Type type; ReplyMarkupClickHandlerPtr link; mutable QSharedPointer ripple; @@ -471,8 +471,8 @@ private: namespace internal { -TextSelection unshiftSelection(TextSelection selection, uint16 byLength); -TextSelection shiftSelection(TextSelection selection, uint16 byLength); +TextSelection unshiftSelection(TextSelection selection, uint16_t byLength); +TextSelection shiftSelection(TextSelection selection, uint16_t byLength); inline TextSelection unshiftSelection(TextSelection selection, const Text &byText) { return ::internal::unshiftSelection(selection, byText.length()); } @@ -635,7 +635,7 @@ public: bool hasOutLayout() const { return out() && !isPost(); } - virtual int32 viewsCount() const { + virtual int32_t viewsCount() const { return hasViews() ? 1 : -1; } @@ -669,7 +669,7 @@ public: } virtual void updateReplyMarkup(const MTPReplyMarkup *markup) { } - virtual int32 addToOverview(AddToOverviewMethod method) { + virtual int32_t addToOverview(AddToOverviewMethod method) { return 0; } virtual void eraseFromOverview() { @@ -705,7 +705,7 @@ public: return { QString(), EntitiesInText() }; } - virtual void drawInfo(Painter &p, int32 right, int32 bottom, int32 width, bool selected, InfoDisplayType type) const { + virtual void drawInfo(Painter &p, int32_t right, int32_t bottom, int32_t width, bool selected, InfoDisplayType type) const { } virtual ClickHandlerPtr fastShareLink() const { return ClickHandlerPtr(); @@ -715,7 +715,7 @@ public: } virtual void drawFastShare(Painter &p, int left, int top, int outerWidth) const { } - virtual void setViewsCount(int32 count) { + virtual void setViewsCount(int32_t count) { } virtual void setId(MsgId newId); @@ -967,7 +967,7 @@ protected: int _indexInBlock = -1; MTPDmessage::Flags _flags = 0; - mutable int32 _authorNameVersion = 0; + mutable int32_t _authorNameVersion = 0; HistoryItem *previousItem() const { if (_block && _indexInBlock >= 0) { diff --git a/Telegram/SourceFiles/history/history_location_manager.cpp b/Telegram/SourceFiles/history/history_location_manager.cpp index a8be64365..c62e50c7c 100644 --- a/Telegram/SourceFiles/history/history_location_manager.cpp +++ b/Telegram/SourceFiles/history/history_location_manager.cpp @@ -116,8 +116,8 @@ void LocationManager::getData(LocationData *data) { return failed(data); } - int32 w = st::locationSize.width(), h = st::locationSize.height(); - int32 zoom = 13, scale = 1; + int32_t w = st::locationSize.width(), h = st::locationSize.height(); + int32_t zoom = 13, scale = 1; if (cScale() == dbisTwo || cRetina()) { scale = 2; } else { diff --git a/Telegram/SourceFiles/history/history_location_manager.h b/Telegram/SourceFiles/history/history_location_manager.h index b3a28a265..60e07f252 100644 --- a/Telegram/SourceFiles/history/history_location_manager.h +++ b/Telegram/SourceFiles/history/history_location_manager.h @@ -27,7 +27,7 @@ void deinitLocationManager(); class LocationCoords { public: LocationCoords() = default; - LocationCoords(float64 lat, float64 lon) : _lat(lat), _lon(lon) { + LocationCoords(double lat, double lon) : _lat(lat), _lon(lon) { } LocationCoords(const MTPDgeoPoint &point) : _lat(point.vlat.v), _lon(point.vlong.v) { } @@ -43,7 +43,7 @@ public: } private: - static QString asString(float64 value) { + static QString asString(double value) { static constexpr auto kPrecision = 6; return QString::number(value, 'f', kPrecision); } @@ -66,8 +66,8 @@ private: #endif // OS_MAC_OLD } - float64 _lat = 0; - float64 _lon = 0; + double _lat = 0; + double _lon = 0; }; @@ -136,7 +136,7 @@ private: QNetworkAccessManager *manager = nullptr; QMap dataLoadings, imageLoadings; - QMap serverRedirects; + QMap serverRedirects; ImagePtr *notLoadedPlaceholder = nullptr; }; diff --git a/Telegram/SourceFiles/history/history_media.h b/Telegram/SourceFiles/history/history_media.h index c8580ebb3..b4ab131fa 100644 --- a/Telegram/SourceFiles/history/history_media.h +++ b/Telegram/SourceFiles/history/history_media.h @@ -74,7 +74,7 @@ public: virtual void updatePressed(QPoint point) { } - virtual int32 addToOverview(AddToOverviewMethod method) { + virtual int32_t addToOverview(AddToOverviewMethod method) { return 0; } virtual void eraseFromOverview() { @@ -95,7 +95,7 @@ public: virtual bool consumeMessageText(const TextWithEntities &textWithEntities) WARN_UNUSED_RESULT { return false; } - virtual uint16 fullSelectionLength() const WARN_UNUSED_RESULT { + virtual uint16_t fullSelectionLength() const WARN_UNUSED_RESULT { return 0; } TextSelection skipSelection(TextSelection selection) const WARN_UNUSED_RESULT { @@ -215,7 +215,7 @@ public: } protected: - int32 addToOneOverview(MediaOverviewType type, AddToOverviewMethod method) { + int32_t addToOneOverview(MediaOverviewType type, AddToOverviewMethod method) { if (_parent->history()->addToOverview(type, _parent->id, method)) { return (1 << type); } diff --git a/Telegram/SourceFiles/history/history_media_types.cpp b/Telegram/SourceFiles/history/history_media_types.cpp index 0a350680e..a3d774ed7 100644 --- a/Telegram/SourceFiles/history/history_media_types.cpp +++ b/Telegram/SourceFiles/history/history_media_types.cpp @@ -100,8 +100,8 @@ void HistoryInitMedia() { namespace { -int32 documentMaxStatusWidth(DocumentData *document) { - int32 result = st::normalFont->width(formatDownloadText(document->size, document->size)); +int32_t documentMaxStatusWidth(DocumentData *document) { + int32_t result = st::normalFont->width(formatDownloadText(document->size, document->size)); if (auto song = document->song()) { result = qMax(result, st::normalFont->width(formatPlayedText(song->duration, song->duration))); result = qMax(result, st::normalFont->width(formatDurationAndSizeText(song->duration, document->size))); @@ -116,8 +116,8 @@ int32 documentMaxStatusWidth(DocumentData *document) { return result; } -int32 gifMaxStatusWidth(DocumentData *document) { - int32 result = st::normalFont->width(formatDownloadText(document->size, document->size)); +int32_t gifMaxStatusWidth(DocumentData *document) { + int32_t result = st::normalFont->width(formatDownloadText(document->size, document->size)); result = qMax(result, st::normalFont->width(formatGifAndSizeText(document->size))); return result; } @@ -187,7 +187,7 @@ void HistoryFileMedia::setLinks(ClickHandlerPtr &&openl, ClickHandlerPtr &&savel _cancell = std::move(cancell); } -void HistoryFileMedia::setStatusSize(int32 newSize, int32 fullSize, int32 duration, qint64 realDuration) const { +void HistoryFileMedia::setStatusSize(int32_t newSize, int32_t fullSize, int32_t duration, int64_t realDuration) const { _statusSize = newSize; if (_statusSize == FileStatusSizeReady) { _statusText = (duration >= 0) ? formatDurationAndSizeText(duration, fullSize) : (duration < -1 ? formatGifAndSizeText(fullSize) : formatSizeText(fullSize)); @@ -239,7 +239,7 @@ HistoryPhoto::HistoryPhoto(not_null parent, not_null p init(); } -HistoryPhoto::HistoryPhoto(not_null parent, not_null chat, not_null photo, int32 width) : HistoryFileMedia(parent) +HistoryPhoto::HistoryPhoto(not_null parent, not_null chat, not_null photo, int32_t width) : HistoryFileMedia(parent) , _data(photo) { setLinks(MakeShared(_data, chat), MakeShared(_data, chat), MakeShared(_data, chat)); @@ -247,7 +247,7 @@ HistoryPhoto::HistoryPhoto(not_null parent, not_null ch init(); } -HistoryPhoto::HistoryPhoto(not_null parent, not_null chat, const MTPDphoto &photo, int32 width) : HistoryPhoto(parent, chat, App::feedPhoto(photo), width) { +HistoryPhoto::HistoryPhoto(not_null parent, not_null chat, const MTPDphoto &photo, int32_t width) : HistoryPhoto(parent, chat, App::feedPhoto(photo), width) { } HistoryPhoto::HistoryPhoto(not_null parent, const HistoryPhoto &other) : HistoryFileMedia(parent) @@ -269,7 +269,7 @@ void HistoryPhoto::initDimensions() { _caption.setSkipBlock(_parent->skipBlockWidth(), _parent->skipBlockHeight()); } - int32 tw = convertScale(_data->full->width()), th = convertScale(_data->full->height()); + int32_t tw = convertScale(_data->full->width()), th = convertScale(_data->full->height()); if (!tw || !th) { tw = th = 1; } @@ -285,10 +285,10 @@ void HistoryPhoto::initDimensions() { if (_parent->toHistoryMessage()) { bool bubble = _parent->hasBubble(); - int32 minWidth = qMax(st::minPhotoSize, _parent->infoWidth() + 2 * (st::msgDateImgDelta + st::msgDateImgPadding.x())); - int32 maxActualWidth = qMax(tw, minWidth); + int32_t minWidth = qMax(st::minPhotoSize, _parent->infoWidth() + 2 * (st::msgDateImgDelta + st::msgDateImgPadding.x())); + int32_t maxActualWidth = qMax(tw, minWidth); _maxw = qMax(maxActualWidth, th); - _minh = qMax(th, int32(st::minPhotoSize)); + _minh = qMax(th, int32_t(st::minPhotoSize)); if (bubble) { maxActualWidth += st::mediaPadding.left() + st::mediaPadding.right(); _maxw += st::mediaPadding.left() + st::mediaPadding.right(); @@ -337,8 +337,8 @@ int HistoryPhoto::resizeGetHeight(int width) { if (_pixh < 1) _pixh = 1; int minWidth = qMax(st::minPhotoSize, _parent->infoWidth() + 2 * (st::msgDateImgDelta + st::msgDateImgPadding.x())); - _width = qMax(_pixw, int16(minWidth)); - _height = qMax(_pixh, int16(st::minPhotoSize)); + _width = qMax(_pixw, int16_t(minWidth)); + _height = qMax(_pixh, int16_t(st::minPhotoSize)); if (bubble) { _width += st::mediaPadding.left() + st::mediaPadding.right(); _height += st::mediaPadding.top() + st::mediaPadding.bottom(); @@ -416,7 +416,7 @@ void HistoryPhoto::draw(Painter &p, const QRect &r, TextSelection selection, Tim p.drawPixmap(rthumb.topLeft(), pix); } if (radial || (!loaded && !_data->loading())) { - float64 radialOpacity = (radial && loaded && !_data->uploading()) ? _animation->radial.opacity() : 1; + double radialOpacity = (radial && loaded && !_data->uploading()) ? _animation->radial.opacity() : 1; QRect inner(rthumb.x() + (rthumb.width() - st::msgFileSize) / 2, rthumb.y() + (rthumb.height() - st::msgFileSize) / 2, st::msgFileSize, st::msgFileSize); p.setPen(Qt::NoPen); if (selected) { @@ -543,9 +543,9 @@ void HistoryPhoto::updateSentMedia(const MTPMessageMedia &media) { if (photo.type() == mtpc_photo) { auto &sizes = photo.c_photo().vsizes.v; - int32 max = 0; + int32_t max = 0; const MTPDfileLocation *maxLocation = 0; - for (int32 i = 0, l = sizes.size(); i < l; ++i) { + for (int32_t i = 0, l = sizes.size(); i < l; ++i) { char size = 0; const MTPFileLocation *loc = 0; switch (sizes.at(i).type()) { @@ -635,8 +635,8 @@ bool HistoryPhoto::needsBubble() const { return false; } -int32 HistoryPhoto::addToOverview(AddToOverviewMethod method) { - auto result = int32(0); +int32_t HistoryPhoto::addToOverview(AddToOverviewMethod method) { + auto result = int32_t(0); if (_parent->toHistoryMessage()) { result |= addToOneOverview(OverviewPhotos, method); } else { @@ -688,23 +688,23 @@ void HistoryVideo::initDimensions() { _caption.setSkipBlock(_parent->skipBlockWidth(), _parent->skipBlockHeight()); } - int32 tw = convertScale(_data->thumb->width()), th = convertScale(_data->thumb->height()); + int32_t tw = convertScale(_data->thumb->width()), th = convertScale(_data->thumb->height()); if (!tw || !th) { tw = th = 1; } if (tw * st::msgVideoSize.height() > th * st::msgVideoSize.width()) { - th = qRound((st::msgVideoSize.width() / float64(tw)) * th); + th = qRound((st::msgVideoSize.width() / double(tw)) * th); tw = st::msgVideoSize.width(); } else { - tw = qRound((st::msgVideoSize.height() / float64(th)) * tw); + tw = qRound((st::msgVideoSize.height() / double(th)) * tw); th = st::msgVideoSize.height(); } _thumbw = qMax(tw, 1); - int32 minWidth = qMax(st::minPhotoSize, _parent->infoWidth() + 2 * (st::msgDateImgDelta + st::msgDateImgPadding.x())); - minWidth = qMax(minWidth, documentMaxStatusWidth(_data) + 2 * int32(st::msgDateImgDelta + st::msgDateImgPadding.x())); - _maxw = qMax(_thumbw, int32(minWidth)); - _minh = qMax(th, int32(st::minPhotoSize)); + int32_t minWidth = qMax(st::minPhotoSize, _parent->infoWidth() + 2 * (st::msgDateImgDelta + st::msgDateImgPadding.x())); + minWidth = qMax(minWidth, documentMaxStatusWidth(_data) + 2 * int32_t(st::msgDateImgDelta + st::msgDateImgPadding.x())); + _maxw = qMax(_thumbw, int32_t(minWidth)); + _minh = qMax(th, int32_t(st::minPhotoSize)); if (bubble) { _maxw += st::mediaPadding.left() + st::mediaPadding.right(); _minh += st::mediaPadding.top() + st::mediaPadding.bottom(); @@ -726,10 +726,10 @@ int HistoryVideo::resizeGetHeight(int width) { tw = th = 1; } if (tw * st::msgVideoSize.height() > th * st::msgVideoSize.width()) { - th = qRound((st::msgVideoSize.width() / float64(tw)) * th); + th = qRound((st::msgVideoSize.width() / double(tw)) * th); tw = st::msgVideoSize.width(); } else { - tw = qRound((st::msgVideoSize.height() / float64(th)) * tw); + tw = qRound((st::msgVideoSize.height() / double(th)) * tw); th = st::msgVideoSize.height(); } @@ -737,7 +737,7 @@ int HistoryVideo::resizeGetHeight(int width) { width -= st::mediaPadding.left() + st::mediaPadding.right(); } if (width < tw) { - th = qRound((width / float64(tw)) * th); + th = qRound((width / double(tw)) * th); tw = width; } @@ -878,7 +878,7 @@ HistoryTextState HistoryVideo::getState(QPoint point, HistoryStateRequest reques bool loaded = _data->loaded(); - int32 skipx = 0, skipy = 0, width = _width, height = _height; + int32_t skipx = 0, skipy = 0, width = _width, height = _height; bool bubble = _parent->hasBubble(); if (bubble) { @@ -922,7 +922,7 @@ HistoryTextState HistoryVideo::getState(QPoint point, HistoryStateRequest reques return result; } -void HistoryVideo::setStatusSize(int32 newSize) const { +void HistoryVideo::setStatusSize(int32_t newSize) const { HistoryFileMedia::setStatusSize(newSize, _data->size, _data->duration(), 0); } @@ -951,7 +951,7 @@ bool HistoryVideo::needsBubble() const { return false; } -int32 HistoryVideo::addToOverview(AddToOverviewMethod method) { +int32_t HistoryVideo::addToOverview(AddToOverviewMethod method) { return addToOneOverview(OverviewVideos, method); } @@ -961,7 +961,7 @@ void HistoryVideo::eraseFromOverview() { void HistoryVideo::updateStatusText() const { bool showPause = false; - int32 statusSize = 0, realDuration = 0; + int32_t statusSize = 0, realDuration = 0; if (_data->status == FileDownloadFailed || _data->status == FileUploadFailed) { statusSize = FileStatusSizeFailed; } else if (_data->status == FileUploading) { @@ -1088,7 +1088,7 @@ HistoryDocument::HistoryDocument(not_null parent, const HistoryDoc } void HistoryDocument::createComponents(bool caption) { - uint64 mask = 0; + uint64_t mask = 0; if (_data->voice()) { mask |= HistoryDocumentVoice::Bit(); } else { @@ -1128,7 +1128,7 @@ void HistoryDocument::initDimensions() { auto thumbed = Get(); if (thumbed) { _data->thumb->load(); - int32 tw = convertScale(_data->thumb->width()), th = convertScale(_data->thumb->height()); + int32_t tw = convertScale(_data->thumb->width()), th = convertScale(_data->thumb->height()); if (tw > th) { thumbed->_thumbw = (tw * st::msgFileThumbSize) / th; } else { @@ -1138,7 +1138,7 @@ void HistoryDocument::initDimensions() { _maxw = st::msgFileMinWidth; - int32 tleft = 0, tright = 0; + int32_t tleft = 0, tright = 0; if (thumbed) { tleft = st::msgFileThumbPadding.left() + st::msgFileThumbSize + st::msgFileThumbPadding.right(); tright = st::msgFileThumbPadding.left(); @@ -1248,7 +1248,7 @@ void HistoryDocument::draw(Painter &p, const QRect &r, TextSelection selection, } if (radial || (!loaded && !_data->loading())) { - float64 radialOpacity = (radial && loaded && !_data->uploading()) ? _animation->radial.opacity() : 1; + double radialOpacity = (radial && loaded && !_data->uploading()) ? _animation->radial.opacity() : 1; QRect inner(rthumb.x() + (rthumb.width() - st::msgFileSize) / 2, rthumb.y() + (rthumb.height() - st::msgFileSize) / 2, st::msgFileSize, st::msgFileSize); p.setPen(Qt::NoPen); if (selected) { @@ -1459,7 +1459,7 @@ HistoryTextState HistoryDocument::getState(QPoint point, HistoryStateRequest req bool showPause = updateStatusText(); - int32 nameleft = 0, nametop = 0, nameright = 0, statustop = 0, linktop = 0, bottom = 0; + int32_t nameleft = 0, nametop = 0, nameright = 0, statustop = 0, linktop = 0, bottom = 0; auto topMinus = isBubbleTop() ? 0 : st::msgFileTopMinus; if (auto thumbed = Get()) { nameleft = st::msgFileThumbPadding.left() + st::msgFileThumbSize + st::msgFileThumbPadding.right(); @@ -1501,7 +1501,7 @@ HistoryTextState HistoryDocument::getState(QPoint point, HistoryStateRequest req auto state = Media::Player::mixer()->currentState(AudioMsgId::Type::Voice); if (state.id == AudioMsgId(_data, _parent->fullId()) && !Media::Player::IsStoppedOrStopping(state.state)) { if (!voice->seeking()) { - voice->setSeekingStart((point.x() - nameleft) / float64(namewidth)); + voice->setSeekingStart((point.x() - nameleft) / double(namewidth)); } result.link = voice->_seekl; return result; @@ -1539,7 +1539,7 @@ void HistoryDocument::updatePressed(QPoint point) { nameleft = st::msgFilePadding.left() + st::msgFileSize + st::msgFilePadding.right(); nameright = st::msgFilePadding.left(); } - voice->setSeekingCurrent(snap((point.x() - nameleft) / float64(_width - nameleft - nameright), 0., 1.)); + voice->setSeekingCurrent(snap((point.x() - nameleft) / double(_width - nameleft - nameright), 0., 1.)); Ui::repaintHistoryItem(_parent); } } @@ -1573,8 +1573,8 @@ TextWithEntities HistoryDocument::selectedText(TextSelection selection) const { return result; } -int32 HistoryDocument::addToOverview(AddToOverviewMethod method) { - auto result = int32(0); +int32_t HistoryDocument::addToOverview(AddToOverviewMethod method) { + auto result = int32_t(0); if (_data->voice()) { result |= addToOneOverview(OverviewVoiceFiles, method); result |= addToOneOverview(OverviewRoundVoiceFiles, method); @@ -1624,8 +1624,8 @@ void HistoryDocument::buildStringRepresentation(Callback callback) const { return callback(attachType, attachFileName, *caption); } -void HistoryDocument::setStatusSize(int32 newSize, qint64 realDuration) const { - int32 duration = _data->song() ? _data->song()->duration : (_data->voice() ? _data->voice()->duration : -1); +void HistoryDocument::setStatusSize(int32_t newSize, int64_t realDuration) const { + int32_t duration = _data->song() ? _data->song()->duration : (_data->voice() ? _data->voice()->duration : -1); HistoryFileMedia::setStatusSize(newSize, _data->size, duration, realDuration); if (auto thumbed = Get()) { if (_statusSize == FileStatusSizeReady) { @@ -1645,7 +1645,7 @@ void HistoryDocument::setStatusSize(int32 newSize, qint64 realDuration) const { bool HistoryDocument::updateStatusText() const { bool showPause = false; - int32 statusSize = 0, realDuration = 0; + int32_t statusSize = 0, realDuration = 0; if (_data->status == FileDownloadFailed || _data->status == FileUploadFailed) { statusSize = FileStatusSizeFailed; } else if (_data->status == FileUploading) { @@ -1662,7 +1662,7 @@ bool HistoryDocument::updateStatusText() const { bool was = (voice->_playback != nullptr); voice->ensurePlayback(this); if (!was || state.position != voice->_playback->_position) { - auto prg = state.length ? snap(float64(state.position) / state.length, 0., 1.) : 0.; + auto prg = state.length ? snap(double(state.position) / state.length, 0., 1.) : 0.; if (voice->_playback->_position < state.position) { voice->_playback->a_progress.start(prg); } else { @@ -1710,10 +1710,10 @@ QMargins HistoryDocument::bubbleMargins() const { return Get() ? QMargins(st::msgFileThumbPadding.left(), st::msgFileThumbPadding.top(), st::msgFileThumbPadding.left(), st::msgFileThumbPadding.bottom()) : st::msgPadding; } -void HistoryDocument::step_voiceProgress(float64 ms, bool timer) { +void HistoryDocument::step_voiceProgress(double ms, bool timer) { if (auto voice = Get()) { if (voice->_playback) { - float64 dt = ms / (2 * AudioVoiceMsgUpdateView); + double dt = ms / (2 * AudioVoiceMsgUpdateView); if (dt >= 1) { voice->_playback->_a_progress.stop(); voice->_playback->a_progress.finish(); @@ -1825,7 +1825,7 @@ void HistoryGif::initDimensions() { } bool bubble = _parent->hasBubble(); - int32 tw = 0, th = 0; + int32_t tw = 0, th = 0; if (_gif && _gif->state() == Media::Clip::State::Error) { if (!_gif->autoplay()) { Ui::show(Box(lang(lng_gif_error))); @@ -1856,11 +1856,11 @@ void HistoryGif::initDimensions() { } _thumbw = tw; _thumbh = th; - _maxw = qMax(tw, int32(st::minPhotoSize)); - _minh = qMax(th, int32(st::minPhotoSize)); - _maxw = qMax(_maxw, _parent->infoWidth() + 2 * int32(st::msgDateImgDelta + st::msgDateImgPadding.x())); + _maxw = qMax(tw, int32_t(st::minPhotoSize)); + _minh = qMax(th, int32_t(st::minPhotoSize)); + _maxw = qMax(_maxw, _parent->infoWidth() + 2 * int32_t(st::msgDateImgDelta + st::msgDateImgPadding.x())); if (!_gif || !_gif->ready()) { - _maxw = qMax(_maxw, gifMaxStatusWidth(_data) + 2 * int32(st::msgDateImgDelta + st::msgDateImgPadding.x())); + _maxw = qMax(_maxw, gifMaxStatusWidth(_data) + 2 * int32_t(st::msgDateImgDelta + st::msgDateImgPadding.x())); } if (bubble) { _maxw += st::mediaPadding.left() + st::mediaPadding.right(); @@ -1913,15 +1913,15 @@ int HistoryGif::resizeGetHeight(int width) { width -= st::mediaPadding.left() + st::mediaPadding.right(); } if (width < tw) { - th = qRound((width / float64(tw)) * th); + th = qRound((width / double(tw)) * th); tw = width; } _thumbw = tw; _thumbh = th; - _width = qMax(tw, int32(st::minPhotoSize)); - _height = qMax(th, int32(st::minPhotoSize)); - _width = qMax(_width, _parent->infoWidth() + 2 * int32(st::msgDateImgDelta + st::msgDateImgPadding.x())); + _width = qMax(tw, int32_t(st::minPhotoSize)); + _height = qMax(th, int32_t(st::minPhotoSize)); + _width = qMax(_width, _parent->infoWidth() + 2 * int32_t(st::msgDateImgDelta + st::msgDateImgPadding.x())); if (_gif && _gif->ready()) { if (!_gif->started()) { auto isRound = _data->isRoundVideo(); @@ -1932,7 +1932,7 @@ int HistoryGif::resizeGetHeight(int width) { _gif->start(_thumbw, _thumbh, _width, _height, roundRadius, roundCorners); } } else { - _width = qMax(_width, gifMaxStatusWidth(_data) + 2 * int32(st::msgDateImgDelta + st::msgDateImgPadding.x())); + _width = qMax(_width, gifMaxStatusWidth(_data) + 2 * int32_t(st::msgDateImgDelta + st::msgDateImgPadding.x())); } if (bubble) { _width += st::mediaPadding.left() + st::mediaPadding.right(); @@ -1979,7 +1979,7 @@ void HistoryGif::draw(Painter &p, const QRect &r, TextSelection selection, TimeM Ui::autoplayMediaInlineAsync(_parent->fullId()); } - int32 skipx = 0, skipy = 0, width = _width, height = _height; + int32_t skipx = 0, skipy = 0, width = _width, height = _height; bool bubble = _parent->hasBubble(); bool out = _parent->out(), isPost = _parent->isPost(), outbg = out && !isPost; auto isChildMedia = (_parent->getMedia() != this); @@ -2247,7 +2247,7 @@ HistoryTextState HistoryGif::getState(QPoint point, HistoryStateRequest request) HistoryTextState result; if (_width < st::msgPadding.left() + st::msgPadding.right() + 1) return result; - int32 skipx = 0, skipy = 0, width = _width, height = _height; + int32_t skipx = 0, skipy = 0, width = _width, height = _height; bool bubble = _parent->hasBubble(); if (bubble) { @@ -2415,8 +2415,8 @@ bool HistoryGif::needsBubble() const { return false; } -int32 HistoryGif::addToOverview(AddToOverviewMethod method) { - auto result = int32(0); +int32_t HistoryGif::addToOverview(AddToOverviewMethod method) { + auto result = int32_t(0); if (_data->isRoundVideo()) { result |= addToOneOverview(OverviewRoundVoiceFiles, method); } else if (_data->isGifv()) { @@ -2445,7 +2445,7 @@ bool HistoryGif::isSeparateRoundVideo() const { return _data->isRoundVideo() && (_parent->getMedia() == this) && !_parent->hasBubble(); } -void HistoryGif::setStatusSize(int32 newSize) const { +void HistoryGif::setStatusSize(int32_t newSize) const { if (_data->isRoundVideo()) { _statusSize = newSize; if (newSize < 0) { @@ -2460,7 +2460,7 @@ void HistoryGif::setStatusSize(int32 newSize) const { void HistoryGif::updateStatusText() const { bool showPause = false; - int32 statusSize = 0, realDuration = 0; + int32_t statusSize = 0, realDuration = 0; if (_data->status == FileDownloadFailed || _data->status == FileUploadFailed) { statusSize = FileStatusSizeFailed; } else if (_data->status == FileUploading) { @@ -2475,7 +2475,7 @@ void HistoryGif::updateStatusText() const { auto state = Media::Player::mixer()->currentState(AudioMsgId::Type::Voice); if (state.id == _gif->audioMsgId()) { if (state.length) { - auto position = int64(0); + auto position = int64_t(0); if (Media::Player::IsStoppedAtEnd(state.state)) { position = state.length; } else if (!Media::Player::IsStoppedOrStopping(state.state)) { @@ -2572,7 +2572,7 @@ bool HistoryGif::playInline(bool autoplay) { }, mode)); if (mode == Mode::Video) { _roundPlayback = std::make_unique(); - _roundPlayback->setValueChangedCallback([this](float64 value) { + _roundPlayback->setValueChangedCallback([this](double value) { Ui::repaintHistoryItem(_parent); }); if (App::main()) { @@ -2615,7 +2615,7 @@ HistoryGif::~HistoryGif() { clearClipReader(); } -float64 HistoryGif::dataProgress() const { +double HistoryGif::dataProgress() const { return (_data->uploading() || !_parent || _parent->id > 0) ? _data->progress() : 0; } @@ -2660,8 +2660,8 @@ void HistorySticker::initDimensions() { } if (_pixw < 1) _pixw = 1; if (_pixh < 1) _pixh = 1; - _maxw = qMax(_pixw, int16(st::minPhotoSize)); - _minh = qMax(_pixh, int16(st::minPhotoSize)); + _maxw = qMax(_pixw, int16_t(st::minPhotoSize)); + _minh = qMax(_pixh, int16_t(st::minPhotoSize)); if (_parent->getMedia() == this) { _maxw += additionalWidth(); } @@ -2923,7 +2923,7 @@ ClickHandlerPtr addContactClickHandler(HistoryItem *item) { } // namespace -HistoryContact::HistoryContact(not_null parent, int32 userId, const QString &first, const QString &last, const QString &phone) : HistoryMedia(parent) +HistoryContact::HistoryContact(not_null parent, int32_t userId, const QString &first, const QString &last, const QString &phone) : HistoryMedia(parent) , _userId(userId) , _fname(first) , _lname(last) @@ -2950,7 +2950,7 @@ void HistoryContact::initDimensions() { } _linkw = _link.isEmpty() ? 0 : st::semiboldFont->width(_link); - int32 tleft = 0, tright = 0; + int32_t tleft = 0, tright = 0; if (_userId) { tleft = st::msgFileThumbPadding.left() + st::msgFileThumbSize + st::msgFileThumbPadding.right(); tright = st::msgFileThumbPadding.left(); @@ -2980,7 +2980,7 @@ void HistoryContact::initDimensions() { void HistoryContact::draw(Painter &p, const QRect &r, TextSelection selection, TimeMs ms) const { if (_width < st::msgPadding.left() + st::msgPadding.right() + 1) return; - int32 skipx = 0, skipy = 0, width = _width, height = _height; + int32_t skipx = 0, skipy = 0, width = _width, height = _height; bool out = _parent->out(), isPost = _parent->isPost(), outbg = out && !isPost; bool selected = (selection == FullSelection); @@ -2989,7 +2989,7 @@ void HistoryContact::draw(Painter &p, const QRect &r, TextSelection selection, T width = _maxw; } - int32 nameleft = 0, nametop = 0, nameright = 0, statustop = 0, linktop = 0; + int32_t nameleft = 0, nametop = 0, nameright = 0, statustop = 0, linktop = 0; auto topMinus = isBubbleTop() ? 0 : st::msgFileTopMinus; if (_userId) { nameleft = st::msgFileThumbPadding.left() + st::msgFileThumbSize + st::msgFileThumbPadding.right(); @@ -3023,7 +3023,7 @@ void HistoryContact::draw(Painter &p, const QRect &r, TextSelection selection, T _photoEmpty.paint(p, st::msgFilePadding.left(), st::msgFilePadding.top() - topMinus, width, st::msgFileSize); } - int32 namewidth = width - nameleft - nameright; + int32_t namewidth = width - nameleft - nameright; p.setFont(st::semiboldFont); p.setPen(outbg ? (selected ? st::historyFileNameOutFgSelected : st::historyFileNameOutFg) : (selected ? st::historyFileNameInFgSelected : st::historyFileNameInFg)); @@ -3039,7 +3039,7 @@ HistoryTextState HistoryContact::getState(QPoint point, HistoryStateRequest requ HistoryTextState result; bool out = _parent->out(), isPost = _parent->isPost(), outbg = out && !isPost; - int32 nameleft = 0, nametop = 0, nameright = 0, statustop = 0, linktop = 0; + int32_t nameleft = 0, nametop = 0, nameright = 0, statustop = 0, linktop = 0; auto topMinus = isBubbleTop() ? 0 : st::msgFileTopMinus; if (_userId) { nameleft = st::msgFileThumbPadding.left() + st::msgFileThumbSize + st::msgFileThumbPadding.right(); @@ -3213,7 +3213,7 @@ QString siteNameFromUrl(const QString &url) { QString pretty = u.isValid() ? u.toDisplayString() : url; QRegularExpressionMatch m = QRegularExpression(qsl("^[a-zA-Z0-9]+://")).match(pretty); if (m.hasMatch()) pretty = pretty.mid(m.capturedLength()); - int32 slash = pretty.indexOf('/'); + int32_t slash = pretty.indexOf('/'); if (slash > 0) pretty = pretty.mid(0, slash); QStringList components = pretty.split('.', QString::SkipEmptyParts); if (components.size() >= 2) { @@ -3223,12 +3223,12 @@ QString siteNameFromUrl(const QString &url) { return QString(); } -int32 articleThumbWidth(PhotoData *thumb, int32 height) { - int32 w = thumb->medium->width(), h = thumb->medium->height(); +int32_t articleThumbWidth(PhotoData *thumb, int32_t height) { + int32_t w = thumb->medium->width(), h = thumb->medium->height(); return qMax(qMin(height * w / h, height), 1); } -int32 articleThumbHeight(PhotoData *thumb, int32 width) { +int32_t articleThumbHeight(PhotoData *thumb, int32_t width) { return qMax(thumb->medium->height() * width / thumb->medium->width(), 1); } @@ -3417,7 +3417,7 @@ int HistoryWebPage::resizeGetHeight(int width) { _pixh = linesMax * lineHeight; do { _pixw = articleThumbWidth(_data->photo, _pixh); - int32 wleft = width - st::webPagePhotoDelta - qMax(_pixw, int16(lineHeight)); + int32_t wleft = width - st::webPagePhotoDelta - qMax(_pixw, int16_t(lineHeight)); _height = siteNameHeight; @@ -3500,7 +3500,7 @@ int HistoryWebPage::resizeGetHeight(int width) { void HistoryWebPage::draw(Painter &p, const QRect &r, TextSelection selection, TimeMs ms) const { if (_width < st::msgPadding.left() + st::msgPadding.right() + 1) return; - int32 skipx = 0, skipy = 0, width = _width, height = _height; + int32_t skipx = 0, skipy = 0, width = _width, height = _height; bool out = _parent->out(), isPost = _parent->isPost(), outbg = out && !isPost; bool selected = (selection == FullSelection); @@ -3531,11 +3531,11 @@ void HistoryWebPage::draw(Painter &p, const QRect &r, TextSelection selection, T _data->photo->medium->load(false, false); bool full = _data->photo->medium->loaded(); QPixmap pix; - int32 pw = qMax(_pixw, int16(lineHeight)), ph = _pixh; - int32 pixw = _pixw, pixh = articleThumbHeight(_data->photo, _pixw); - int32 maxw = convertScale(_data->photo->medium->width()), maxh = convertScale(_data->photo->medium->height()); + int32_t pw = qMax(_pixw, int16_t(lineHeight)), ph = _pixh; + int32_t pixw = _pixw, pixh = articleThumbHeight(_data->photo, _pixw); + int32_t maxw = convertScale(_data->photo->medium->width()), maxh = convertScale(_data->photo->medium->height()); if (pixw * ph != pixh * pw) { - float64 coef = (pixw * ph > pixh * pw) ? qMin(ph / float64(pixh), maxh / float64(pixh)) : qMin(pw / float64(pixw), maxw / float64(pixw)); + double coef = (pixw * ph > pixh * pw) ? qMin(ph / double(pixh), maxh / double(pixh)) : qMin(pw / double(pixw), maxw / double(pixw)); pixh = qRound(pixh * coef); pixw = qRound(pixw * coef); } @@ -3558,7 +3558,7 @@ void HistoryWebPage::draw(Painter &p, const QRect &r, TextSelection selection, T } if (_titleLines) { p.setPen(outbg ? st::webPageTitleOutFg : st::webPageTitleInFg); - int32 endskip = 0; + int32_t endskip = 0; if (_title.hasSkipBlock()) { endskip = _parent->skipBlockWidth(); } @@ -3567,7 +3567,7 @@ void HistoryWebPage::draw(Painter &p, const QRect &r, TextSelection selection, T } if (_descriptionLines) { p.setPen(outbg ? st::webPageDescriptionOutFg : st::webPageDescriptionInFg); - int32 endskip = 0; + int32_t endskip = 0; if (_description.hasSkipBlock()) { endskip = _parent->skipBlockWidth(); } @@ -3591,7 +3591,7 @@ void HistoryWebPage::draw(Painter &p, const QRect &r, TextSelection selection, T auto attachSelection = selected ? FullSelection : TextSelection { 0, 0 }; _attach->draw(p, r.translated(-attachLeft, -attachTop), attachSelection, ms); - int32 pixwidth = _attach->currentWidth(), pixheight = _attach->height(); + int32_t pixwidth = _attach->currentWidth(), pixheight = _attach->height(); if (_data->type == WebPageVideo && _attach->type() == MediaTypePhoto) { if (_attach->isReadyForOpen()) { @@ -3602,10 +3602,10 @@ void HistoryWebPage::draw(Painter &p, const QRect &r, TextSelection selection, T } } if (_durationWidth) { - int32 dateX = pixwidth - _durationWidth - st::msgDateImgDelta - 2 * st::msgDateImgPadding.x(); - int32 dateY = pixheight - st::msgDateFont->height - 2 * st::msgDateImgPadding.y() - st::msgDateImgDelta; - int32 dateW = pixwidth - dateX - st::msgDateImgDelta; - int32 dateH = pixheight - dateY - st::msgDateImgDelta; + int32_t dateX = pixwidth - _durationWidth - st::msgDateImgDelta - 2 * st::msgDateImgPadding.x(); + int32_t dateY = pixheight - st::msgDateFont->height - 2 * st::msgDateImgPadding.y() - st::msgDateImgDelta; + int32_t dateW = pixwidth - dateX - st::msgDateImgDelta; + int32_t dateH = pixheight - dateY - st::msgDateImgDelta; App::roundRect(p, dateX, dateY, dateW, dateH, selected ? st::msgDateImgBgSelected : st::msgDateImgBg, selected ? DateSelectedCorners : DateCorners); @@ -3629,7 +3629,7 @@ HistoryTextState HistoryWebPage::getState(QPoint point, HistoryStateRequest requ HistoryTextState result; if (_width < st::msgPadding.left() + st::msgPadding.right() + 1) return result; - int32 skipx = 0, skipy = 0, width = _width, height = _height; + int32_t skipx = 0, skipy = 0, width = _width, height = _height; QMargins bubble(_attach ? _attach->bubbleMargins() : QMargins()); auto padding = inBubblePadding(); @@ -3643,7 +3643,7 @@ HistoryTextState HistoryWebPage::getState(QPoint point, HistoryStateRequest requ auto lineHeight = unitedLineHeight(); auto inThumb = false; if (_asArticle) { - int32 pw = qMax(_pixw, int16(lineHeight)); + int32_t pw = qMax(_pixw, int16_t(lineHeight)); if (rtlrect(padding.left() + width - pw, 0, pw, _pixh, _width).contains(point)) { inThumb = true; } @@ -3848,15 +3848,15 @@ void HistoryGame::initDimensions() { } // init dimensions - int32 l = st::msgPadding.left() + st::webPageLeft, r = st::msgPadding.right(); - int32 skipBlockWidth = _parent->skipBlockWidth(); + int32_t l = st::msgPadding.left() + st::webPageLeft, r = st::msgPadding.right(); + int32_t skipBlockWidth = _parent->skipBlockWidth(); _maxw = skipBlockWidth; _minh = 0; - int32 titleMinHeight = _title.isEmpty() ? 0 : lineHeight; + int32_t titleMinHeight = _title.isEmpty() ? 0 : lineHeight; // enable any count of lines in game description / message int descMaxLines = 4096; - int32 descriptionMinHeight = _description.isEmpty() ? 0 : qMin(_description.minHeight(), descMaxLines * lineHeight); + int32_t descriptionMinHeight = _description.isEmpty() ? 0 : qMin(_description.minHeight(), descMaxLines * lineHeight); if (!_title.isEmpty()) { accumulate_max(_maxw, _title.maxWidth()); @@ -3916,7 +3916,7 @@ int HistoryGame::resizeGetHeight(int width) { if (_description.isEmpty()) { _descriptionLines = 0; } else { - int32 descriptionHeight = _description.countHeight(width); + int32_t descriptionHeight = _description.countHeight(width); if (descriptionHeight < (linesMax - _titleLines) * st::webPageDescriptionFont->height) { _descriptionLines = (descriptionHeight / st::webPageDescriptionFont->height); } else { @@ -3945,7 +3945,7 @@ int HistoryGame::resizeGetHeight(int width) { void HistoryGame::draw(Painter &p, const QRect &r, TextSelection selection, TimeMs ms) const { if (_width < st::msgPadding.left() + st::msgPadding.right() + 1) return; - int32 width = _width, height = _height; + int32_t width = _width, height = _height; bool out = _parent->out(), isPost = _parent->isPost(), outbg = out && !isPost; bool selected = (selection == FullSelection); @@ -3969,7 +3969,7 @@ void HistoryGame::draw(Painter &p, const QRect &r, TextSelection selection, Time auto lineHeight = unitedLineHeight(); if (_titleLines) { p.setPen(semibold); - int32 endskip = 0; + int32_t endskip = 0; if (_title.hasSkipBlock()) { endskip = _parent->skipBlockWidth(); } @@ -3978,7 +3978,7 @@ void HistoryGame::draw(Painter &p, const QRect &r, TextSelection selection, Time } if (_descriptionLines) { p.setPen(outbg ? st::webPageDescriptionOutFg : st::webPageDescriptionInFg); - int32 endskip = 0; + int32_t endskip = 0; if (_description.hasSkipBlock()) { endskip = _parent->skipBlockWidth(); } @@ -4019,7 +4019,7 @@ HistoryTextState HistoryGame::getState(QPoint point, HistoryStateRequest request HistoryTextState result; if (_width < st::msgPadding.left() + st::msgPadding.right() + 1) return result; - int32 width = _width, height = _height; + int32_t width = _width, height = _height; QMargins bubble(_attach ? _attach->bubbleMargins() : QMargins()); auto padding = inBubblePadding(); @@ -4288,15 +4288,15 @@ void HistoryInvoice::initDimensions() { } // init dimensions - int32 l = st::msgPadding.left(), r = st::msgPadding.right(); - int32 skipBlockWidth = _parent->skipBlockWidth(); + int32_t l = st::msgPadding.left(), r = st::msgPadding.right(); + int32_t skipBlockWidth = _parent->skipBlockWidth(); _maxw = skipBlockWidth; _minh = 0; - int32 titleMinHeight = _title.isEmpty() ? 0 : lineHeight; + int32_t titleMinHeight = _title.isEmpty() ? 0 : lineHeight; // enable any count of lines in game description / message int descMaxLines = 4096; - int32 descriptionMinHeight = _description.isEmpty() ? 0 : qMin(_description.minHeight(), descMaxLines * lineHeight); + int32_t descriptionMinHeight = _description.isEmpty() ? 0 : qMin(_description.minHeight(), descMaxLines * lineHeight); if (!_title.isEmpty()) { accumulate_max(_maxw, _title.maxWidth()); @@ -4374,7 +4374,7 @@ int HistoryInvoice::resizeGetHeight(int width) { void HistoryInvoice::draw(Painter &p, const QRect &r, TextSelection selection, TimeMs ms) const { if (_width < st::msgPadding.left() + st::msgPadding.right() + 1) return; - int32 width = _width, height = _height; + int32_t width = _width, height = _height; bool out = _parent->out(), isPost = _parent->isPost(), outbg = out && !isPost; bool selected = (selection == FullSelection); @@ -4397,7 +4397,7 @@ void HistoryInvoice::draw(Painter &p, const QRect &r, TextSelection selection, T p.setPen(semibold); p.setTextPalette(selected ? (outbg ? st::outTextPaletteSelected : st::inTextPaletteSelected) : (outbg ? st::outSemiboldPalette : st::inSemiboldPalette)); - int32 endskip = 0; + int32_t endskip = 0; if (_title.hasSkipBlock()) { endskip = _parent->skipBlockWidth(); } @@ -4449,7 +4449,7 @@ HistoryTextState HistoryInvoice::getState(QPoint point, HistoryStateRequest requ HistoryTextState result; if (_width < st::msgPadding.left() + st::msgPadding.right() + 1) return result; - int32 width = _width, height = _height; + int32_t width = _width, height = _height; QMargins bubble(_attach ? _attach->bubbleMargins() : QMargins()); auto padding = inBubblePadding(); @@ -4591,14 +4591,14 @@ HistoryLocation::HistoryLocation(not_null parent, const HistoryLoc void HistoryLocation::initDimensions() { bool bubble = _parent->hasBubble(); - int32 tw = fullWidth(), th = fullHeight(); + int32_t tw = fullWidth(), th = fullHeight(); if (tw > st::maxMediaSize) { th = (st::maxMediaSize * th) / tw; tw = st::maxMediaSize; } - int32 minWidth = qMax(st::minPhotoSize, _parent->infoWidth() + 2 * (st::msgDateImgDelta + st::msgDateImgPadding.x())); - _maxw = qMax(tw, int32(minWidth)); - _minh = qMax(th, int32(st::minPhotoSize)); + int32_t minWidth = qMax(st::minPhotoSize, _parent->infoWidth() + 2 * (st::msgDateImgDelta + st::msgDateImgPadding.x())); + _maxw = qMax(tw, int32_t(minWidth)); + _minh = qMax(th, int32_t(st::minPhotoSize)); if (bubble) { _maxw += st::mediaPadding.left() + st::mediaPadding.right(); @@ -4626,7 +4626,7 @@ int HistoryLocation::resizeGetHeight(int width) { _width -= st::mediaPadding.left() + st::mediaPadding.right(); } - int32 tw = fullWidth(), th = fullHeight(); + int32_t tw = fullWidth(), th = fullHeight(); if (tw > st::maxMediaSize) { th = (st::maxMediaSize * th) / tw; tw = st::maxMediaSize; @@ -4637,9 +4637,9 @@ int HistoryLocation::resizeGetHeight(int width) { } else { _width = tw; } - int32 minWidth = qMax(st::minPhotoSize, _parent->infoWidth() + 2 * (st::msgDateImgDelta + st::msgDateImgPadding.x())); - _width = qMax(_width, int32(minWidth)); - _height = qMax(_height, int32(st::minPhotoSize)); + int32_t minWidth = qMax(st::minPhotoSize, _parent->infoWidth() + 2 * (st::msgDateImgDelta + st::msgDateImgPadding.x())); + _width = qMax(_width, int32_t(minWidth)); + _height = qMax(_height, int32_t(st::minPhotoSize)); if (bubble) { _width += st::mediaPadding.left() + st::mediaPadding.right(); _height += st::mediaPadding.top() + st::mediaPadding.bottom(); @@ -4661,7 +4661,7 @@ int HistoryLocation::resizeGetHeight(int width) { void HistoryLocation::draw(Painter &p, const QRect &r, TextSelection selection, TimeMs ms) const { if (_width < st::msgPadding.left() + st::msgPadding.right() + 1) return; - int32 skipx = 0, skipy = 0, width = _width, height = _height; + int32_t skipx = 0, skipy = 0, width = _width, height = _height; bool bubble = _parent->hasBubble(); bool out = _parent->out(), isPost = _parent->isPost(), outbg = out && !isPost; bool selected = (selection == FullSelection); @@ -4677,7 +4677,7 @@ void HistoryLocation::draw(Painter &p, const QRect &r, TextSelection selection, } width -= st::mediaPadding.left() + st::mediaPadding.right(); - int32 textw = _width - st::msgPadding.left() - st::msgPadding.right(); + int32_t textw = _width - st::msgPadding.left() - st::msgPadding.right(); if (!_title.isEmpty()) { p.setPen(outbg ? st::webPageTitleOutFg : st::webPageTitleInFg); @@ -4703,15 +4703,15 @@ void HistoryLocation::draw(Painter &p, const QRect &r, TextSelection selection, | (isBubbleBottom() ? (ImageRoundCorner::BottomLeft | ImageRoundCorner::BottomRight) : ImageRoundCorner::None); auto rthumb = QRect(skipx, skipy, width, height); if (_data && !_data->thumb->isNull()) { - int32 w = _data->thumb->width(), h = _data->thumb->height(); + int32_t w = _data->thumb->width(), h = _data->thumb->height(); QPixmap pix; if (width * h == height * w || (w == fullWidth() && h == fullHeight())) { pix = _data->thumb->pixSingle(width, height, width, height, roundRadius, roundCorners); } else if (width * h > height * w) { - int32 nw = height * w / h; + int32_t nw = height * w / h; pix = _data->thumb->pixSingle(nw, height, width, height, roundRadius, roundCorners); } else { - int32 nh = width * h / w; + int32_t nh = width * h / w; pix = _data->thumb->pixSingle(width, nh, width, height, roundRadius, roundCorners); } p.drawPixmap(rthumb.topLeft(), pix); @@ -4739,7 +4739,7 @@ HistoryTextState HistoryLocation::getState(QPoint point, HistoryStateRequest req auto symbolAdd = 0; if (_width < st::msgPadding.left() + st::msgPadding.right() + 1) return result; - int32 skipx = 0, skipy = 0, width = _width, height = _height; + int32_t skipx = 0, skipy = 0, width = _width, height = _height; bool bubble = _parent->hasBubble(); if (bubble) { @@ -4857,10 +4857,10 @@ bool HistoryLocation::needsBubble() const { return false; } -int32 HistoryLocation::fullWidth() const { +int32_t HistoryLocation::fullWidth() const { return st::locationSize.width(); } -int32 HistoryLocation::fullHeight() const { +int32_t HistoryLocation::fullHeight() const { return st::locationSize.height(); } diff --git a/Telegram/SourceFiles/history/history_media_types.h b/Telegram/SourceFiles/history/history_media_types.h index 5a77b7f42..35e576fa1 100644 --- a/Telegram/SourceFiles/history/history_media_types.h +++ b/Telegram/SourceFiles/history/history_media_types.h @@ -76,11 +76,11 @@ protected: // 0x7FFFFFF0 will contain status for not yet downloaded file // 0x7FFFFFF1 will contain status for already downloaded file // 0x7FFFFFF2 will contain status for failed to download / upload file - mutable int32 _statusSize; + mutable int32_t _statusSize; mutable QString _statusText; // duration = -1 - no duration, duration = -2 - "GIF" duration - void setStatusSize(int32 newSize, int32 fullSize, int32 duration, qint64 realDuration) const; + void setStatusSize(int32_t newSize, int32_t fullSize, int32_t duration, int64_t realDuration) const; void step_radial(TimeMs ms, bool timer); void thumbAnimationCallback(); @@ -104,7 +104,7 @@ protected: return false; } - virtual float64 dataProgress() const = 0; + virtual double dataProgress() const = 0; virtual bool dataFinished() const = 0; virtual bool dataLoaded() const = 0; @@ -143,7 +143,7 @@ public: TextSelection adjustSelection(TextSelection selection, TextSelectType type) const override WARN_UNUSED_RESULT { return _caption.adjustSelection(selection, type); } - uint16 fullSelectionLength() const override { + uint16_t fullSelectionLength() const override { return _caption.length(); } bool hasTextForCopy() const override { @@ -154,7 +154,7 @@ public: QString inDialogsText() const override; TextWithEntities selectedText(TextSelection selection) const override; - int32 addToOverview(AddToOverviewMethod method) override; + int32_t addToOverview(AddToOverviewMethod method) override; void eraseFromOverview() override; PhotoData *photo() const { @@ -190,7 +190,7 @@ public: } protected: - float64 dataProgress() const override { + double dataProgress() const override { return _data->progress(); } bool dataFinished() const override { @@ -202,8 +202,8 @@ protected: private: not_null _data; - int16 _pixw = 1; - int16 _pixh = 1; + int16_t _pixw = 1; + int16_t _pixh = 1; Text _caption; }; @@ -228,7 +228,7 @@ public: TextSelection adjustSelection(TextSelection selection, TextSelectType type) const override WARN_UNUSED_RESULT { return _caption.adjustSelection(selection, type); } - uint16 fullSelectionLength() const override { + uint16_t fullSelectionLength() const override { return _caption.length(); } bool hasTextForCopy() const override { @@ -239,7 +239,7 @@ public: QString inDialogsText() const override; TextWithEntities selectedText(TextSelection selection) const override; - int32 addToOverview(AddToOverviewMethod method) override; + int32_t addToOverview(AddToOverviewMethod method) override; void eraseFromOverview() override; DocumentData *getDocument() override { @@ -276,7 +276,7 @@ public: } protected: - float64 dataProgress() const override { + double dataProgress() const override { return _data->progress(); } bool dataFinished() const override { @@ -288,10 +288,10 @@ protected: private: not_null _data; - int32 _thumbw; + int32_t _thumbw; Text _caption; - void setStatusSize(int32 newSize) const; + void setStatusSize(int32_t newSize) const; void updateStatusText() const; }; @@ -316,13 +316,13 @@ class HistoryDocument; struct HistoryDocumentVoicePlayback { HistoryDocumentVoicePlayback(const HistoryDocument *that); - int32 _position = 0; + int32_t _position = 0; anim::value a_progress; BasicAnimation _a_progress; }; class HistoryDocumentVoice : public RuntimeComponent { - // We don't use float64 because components should align to pointer even on 32bit systems. - static constexpr float64 kFloatToIntMultiplier = 65536.; + // We don't use double because components should align to pointer even on 32bit systems. + static constexpr double kFloatToIntMultiplier = 65536.; public: void ensurePlayback(const HistoryDocument *interfaces) const; @@ -337,16 +337,16 @@ public: } void startSeeking(); void stopSeeking(); - float64 seekingStart() const { + double seekingStart() const { return _seekingStart / kFloatToIntMultiplier; } - void setSeekingStart(float64 seekingStart) const { + void setSeekingStart(double seekingStart) const { _seekingStart = qRound(seekingStart * kFloatToIntMultiplier); } - float64 seekingCurrent() const { + double seekingCurrent() const { return _seekingCurrent / kFloatToIntMultiplier; } - void setSeekingCurrent(float64 seekingCurrent) { + void setSeekingCurrent(double seekingCurrent) { _seekingCurrent = qRound(seekingCurrent * kFloatToIntMultiplier); } @@ -382,7 +382,7 @@ public: } return selection; } - uint16 fullSelectionLength() const override { + uint16_t fullSelectionLength() const override { if (auto captioned = Get()) { return captioned->_caption.length(); } @@ -396,7 +396,7 @@ public: QString inDialogsText() const override; TextWithEntities selectedText(TextSelection selection) const override; - int32 addToOverview(AddToOverviewMethod method) override; + int32_t addToOverview(AddToOverviewMethod method) override; void eraseFromOverview() override; bool uploading() const override { @@ -440,12 +440,12 @@ public: return true; } - void step_voiceProgress(float64 ms, bool timer); + void step_voiceProgress(double ms, bool timer); void clickHandlerPressedChanged(const ClickHandlerPtr &p, bool pressed) override; protected: - float64 dataProgress() const override { + double dataProgress() const override { return _data->progress(); } bool dataFinished() const override { @@ -459,7 +459,7 @@ private: void createComponents(bool caption); void fillNamedFromData(HistoryDocumentNamed *named); - void setStatusSize(int32 newSize, qint64 realDuration = 0) const; + void setStatusSize(int32_t newSize, int64_t realDuration = 0) const; bool updateStatusText() const; // returns showPause // Callback is a void(const QString &, const QString &, const Text &) functor. @@ -491,7 +491,7 @@ public: TextSelection adjustSelection(TextSelection selection, TextSelectType type) const override WARN_UNUSED_RESULT { return _caption.adjustSelection(selection, type); } - uint16 fullSelectionLength() const override { + uint16_t fullSelectionLength() const override { return _caption.length(); } bool hasTextForCopy() const override { @@ -502,7 +502,7 @@ public: QString inDialogsText() const override; TextWithEntities selectedText(TextSelection selection) const override; - int32 addToOverview(AddToOverviewMethod method) override; + int32_t addToOverview(AddToOverviewMethod method) override; void eraseFromOverview() override; bool uploading() const override { @@ -553,7 +553,7 @@ public: ~HistoryGif(); protected: - float64 dataProgress() const override; + double dataProgress() const override; bool dataFinished() const override; bool dataLoaded() const override; @@ -572,14 +572,14 @@ private: not_null _data; ClickHandlerPtr _openInMediaviewLink; - int32 _thumbw = 1; - int32 _thumbh = 1; + int32_t _thumbw = 1; + int32_t _thumbh = 1; Text _caption; mutable std::unique_ptr _roundPlayback; Media::Clip::ReaderPointer _gif; - void setStatusSize(int32 newSize) const; + void setStatusSize(int32_t newSize) const; void updateStatusText() const; }; @@ -645,8 +645,8 @@ private: } QString toString() const; - int16 _pixw = 1; - int16 _pixh = 1; + int16_t _pixw = 1; + int16_t _pixh = 1; ClickHandlerPtr _packLink; not_null _data; QString _emoji; @@ -655,7 +655,7 @@ private: class HistoryContact : public HistoryMedia { public: - HistoryContact(not_null parent, int32 userId, const QString &first, const QString &last, const QString &phone); + HistoryContact(not_null parent, int32_t userId, const QString &first, const QString &last, const QString &phone); HistoryMediaType type() const override { return MediaTypeContact; } @@ -701,7 +701,7 @@ public: } private: - int32 _userId = 0; + int32_t _userId = 0; UserData *_contact = nullptr; int _phonew = 0; @@ -788,7 +788,7 @@ public: HistoryTextState getState(QPoint point, HistoryStateRequest request) const override; TextSelection adjustSelection(TextSelection selection, TextSelectType type) const override WARN_UNUSED_RESULT; - uint16 fullSelectionLength() const override { + uint16_t fullSelectionLength() const override { return _title.length() + _description.length(); } bool hasTextForCopy() const override { @@ -863,16 +863,16 @@ private: std::unique_ptr _attach; bool _asArticle = false; - int32 _titleLines, _descriptionLines; + int32_t _titleLines, _descriptionLines; Text _title, _description; - int32 _siteNameWidth = 0; + int32_t _siteNameWidth = 0; QString _duration; - int32 _durationWidth = 0; + int32_t _durationWidth = 0; - int16 _pixw = 0; - int16 _pixh = 0; + int16_t _pixw = 0; + int16_t _pixh = 0; }; @@ -895,7 +895,7 @@ public: HistoryTextState getState(QPoint point, HistoryStateRequest request) const override; TextSelection adjustSelection(TextSelection selection, TextSelectType type) const override WARN_UNUSED_RESULT; - uint16 fullSelectionLength() const override { + uint16_t fullSelectionLength() const override { return _title.length() + _description.length(); } bool isAboveMessage() const override { @@ -975,7 +975,7 @@ private: ClickHandlerPtr _openl; std::unique_ptr _attach; - int32 _titleLines, _descriptionLines; + int32_t _titleLines, _descriptionLines; Text _title, _description; @@ -1009,7 +1009,7 @@ public: HistoryTextState getState(QPoint point, HistoryStateRequest request) const override; TextSelection adjustSelection(TextSelection selection, TextSelectType type) const override WARN_UNUSED_RESULT; - uint16 fullSelectionLength() const override { + uint16_t fullSelectionLength() const override { return _title.length() + _description.length(); } bool hasTextForCopy() const override { @@ -1089,13 +1089,13 @@ public: } void initDimensions() override; - int resizeGetHeight(int32 width) override; + int resizeGetHeight(int32_t width) override; void draw(Painter &p, const QRect &r, TextSelection selection, TimeMs ms) const override; HistoryTextState getState(QPoint point, HistoryStateRequest request) const override; TextSelection adjustSelection(TextSelection selection, TextSelectType type) const override WARN_UNUSED_RESULT; - uint16 fullSelectionLength() const override { + uint16_t fullSelectionLength() const override { return _title.length() + _description.length(); } bool hasTextForCopy() const override { @@ -1134,7 +1134,7 @@ private: Text _title, _description; ClickHandlerPtr _link; - int32 fullWidth() const; - int32 fullHeight() const; + int32_t fullWidth() const; + int32_t fullHeight() const; }; diff --git a/Telegram/SourceFiles/history/history_message.cpp b/Telegram/SourceFiles/history/history_message.cpp index ca4f9289c..0aafba4af 100644 --- a/Telegram/SourceFiles/history/history_message.cpp +++ b/Telegram/SourceFiles/history/history_message.cpp @@ -331,7 +331,7 @@ void HistoryMessageVia::create(UserId userId) { }); } -void HistoryMessageVia::resize(int32 availw) const { +void HistoryMessageVia::resize(int32_t availw) const { if (availw < 0) { _text = QString(); _width = 0; @@ -457,13 +457,13 @@ void HistoryMessageReply::updateName() const { replyToName.setText(st::fwdTextStyle, name, _textNameOptions); replyToVersion = replyToMsg->author()->nameVersion; bool hasPreview = replyToMsg->getMedia() ? replyToMsg->getMedia()->hasReplyPreview() : false; - int32 previewSkip = hasPreview ? (st::msgReplyBarSize.height() + st::msgReplyBarSkip - st::msgReplyBarSize.width() - st::msgReplyBarPos.x()) : 0; - int32 w = replyToName.maxWidth(); + int32_t previewSkip = hasPreview ? (st::msgReplyBarSize.height() + st::msgReplyBarSkip - st::msgReplyBarSize.width() - st::msgReplyBarPos.x()) : 0; + int32_t w = replyToName.maxWidth(); if (_replyToVia) { w += st::msgServiceFont->spacew + _replyToVia->_maxWidth; } - _maxReplyWidth = previewSkip + qMax(w, qMin(replyToText.maxWidth(), int32(st::maxSignatureSize))); + _maxReplyWidth = previewSkip + qMax(w, qMin(replyToText.maxWidth(), int32_t(st::maxSignatureSize))); } else { _maxReplyWidth = st::msgDateFont->width(lang(replyToMsgId ? lng_profile_loading : lng_deleted_message)); } @@ -559,7 +559,7 @@ int HistoryMessage::KeyboardStyle::buttonRadius() const { return st::dateRadius; } -void HistoryMessage::KeyboardStyle::paintButtonBg(Painter &p, const QRect &rect, float64 howMuchOver) const { +void HistoryMessage::KeyboardStyle::paintButtonBg(Painter &p, const QRect &rect, double howMuchOver) const { App::roundRect(p, rect, st::msgServiceBg, StickerCorners); if (howMuchOver > 0) { auto o = p.opacity(); @@ -823,7 +823,7 @@ bool HistoryMessage::displayFastShare() const { } void HistoryMessage::createComponents(const CreateConfig &config) { - uint64 mask = 0; + uint64_t mask = 0; if (config.replyTo) { mask |= HistoryMessageReply::Bit(); } @@ -900,7 +900,7 @@ void HistoryMessage::createComponents(const CreateConfig &config) { initTime(); } -QString formatViewsCount(int32 views) { +QString formatViewsCount(int32_t views) { if (views > 999999) { views /= 100000; if (views % 10) { @@ -1024,7 +1024,7 @@ void HistoryMessage::initMediaFromDocument(DocumentData *doc, const QString &cap } } -int32 HistoryMessage::plainMaxWidth() const { +int32_t HistoryMessage::plainMaxWidth() const { return st::msgPadding.left() + _text.maxWidth() + st::msgPadding.right(); } @@ -1166,7 +1166,7 @@ QRect HistoryMessage::countGeometry() const { return QRect(contentLeft, contentTop, contentWidth, _height - contentTop - marginBottom()); } -void HistoryMessage::fromNameUpdated(int32 width) const { +void HistoryMessage::fromNameUpdated(int32_t width) const { _authorNameVersion = author()->nameVersion; if (!Has()) { if (auto via = Get()) { @@ -1265,10 +1265,10 @@ void HistoryMessage::updateMedia(const MTPMessageMedia *media) { setPendingInitDimensions(); } -int32 HistoryMessage::addToOverview(AddToOverviewMethod method) { +int32_t HistoryMessage::addToOverview(AddToOverviewMethod method) { if (!indexInOverview()) return 0; - int32 result = 0; + int32_t result = 0; if (auto media = getMedia()) { result |= media->addToOverview(method); } @@ -1476,12 +1476,12 @@ int HistoryMessage::timeLeft() const { return result; } -void HistoryMessage::drawInfo(Painter &p, int32 right, int32 bottom, int32 width, bool selected, InfoDisplayType type) const { +void HistoryMessage::drawInfo(Painter &p, int32_t right, int32_t bottom, int32_t width, bool selected, InfoDisplayType type) const { p.setFont(st::msgDateFont); bool outbg = out() && !isPost(); bool invertedsprites = (type == InfoDisplayOverImage || type == InfoDisplayOverBackground); - int32 infoRight = right, infoBottom = bottom; + int32_t infoRight = right, infoBottom = bottom; switch (type) { case InfoDisplayDefault: infoRight -= st::msgPadding.right() - st::msgDateDelta.x(); @@ -1500,16 +1500,16 @@ void HistoryMessage::drawInfo(Painter &p, int32 right, int32 bottom, int32 width break; } - int32 infoW = HistoryMessage::infoWidth(); + int32_t infoW = HistoryMessage::infoWidth(); if (rtl()) infoRight = width - infoRight + infoW; - int32 dateX = infoRight - infoW; - int32 dateY = infoBottom - st::msgDateFont->height; + int32_t dateX = infoRight - infoW; + int32_t dateY = infoBottom - st::msgDateFont->height; if (type == InfoDisplayOverImage) { - int32 dateW = infoW + 2 * st::msgDateImgPadding.x(), dateH = st::msgDateFont->height + 2 * st::msgDateImgPadding.y(); + int32_t dateW = infoW + 2 * st::msgDateImgPadding.x(), dateH = st::msgDateFont->height + 2 * st::msgDateImgPadding.y(); App::roundRect(p, dateX - st::msgDateImgPadding.x(), dateY - st::msgDateImgPadding.y(), dateW, dateH, selected ? st::msgDateImgBgSelected : st::msgDateImgBg, selected ? DateSelectedCorners : DateCorners); } else if (type == InfoDisplayOverBackground) { - int32 dateW = infoW + 2 * st::msgDateImgPadding.x(), dateH = st::msgDateFont->height + 2 * st::msgDateImgPadding.y(); + int32_t dateW = infoW + 2 * st::msgDateImgPadding.x(), dateH = st::msgDateFont->height + 2 * st::msgDateImgPadding.y(); App::roundRect(p, dateX - st::msgDateImgPadding.x(), dateY - st::msgDateImgPadding.y(), dateW, dateH, selected ? st::msgServiceBgSelected : st::msgServiceBg, selected ? StickerSelectedCorners : StickerCorners); } dateX += HistoryMessage::timeLeft(); @@ -1557,11 +1557,11 @@ void HistoryMessage::drawInfo(Painter &p, int32 right, int32 bottom, int32 width } } -void HistoryMessage::setViewsCount(int32 count) { +void HistoryMessage::setViewsCount(int32_t count) { auto views = Get(); if (!views || views->_views == count || (count >= 0 && views->_views > count)) return; - int32 was = views->_viewsWidth; + int32_t was = views->_viewsWidth; views->_views = count; views->_viewsText = (views->_views >= 0) ? formatViewsCount(views->_views) : QString(); views->_viewsWidth = views->_viewsText.isEmpty() ? 0 : st::msgDateFont->width(views->_viewsText); @@ -1623,7 +1623,7 @@ void HistoryMessage::draw(Painter &p, QRect clip, TextSelection selection, TimeM auto skiptop = top - fill; auto fillheight = fill + g.height() + fill; - auto dt = (animms > st::activeFadeInDuration) ? (1. - (animms - st::activeFadeInDuration) / float64(st::activeFadeOutDuration)) : (animms / float64(st::activeFadeInDuration)); + auto dt = (animms > st::activeFadeInDuration) ? (1. - (animms - st::activeFadeInDuration) / double(st::activeFadeOutDuration)) : (animms / double(st::activeFadeInDuration)); auto o = p.opacity(); p.setOpacity(o * dt); p.fillRect(0, skiptop, width(), fillheight, st::defaultTextPalette.selectOverlay); @@ -1781,7 +1781,7 @@ void HistoryMessage::paintForwardedInfo(Painter &p, QRect &trect, bool selected) void HistoryMessage::paintReplyInfo(Painter &p, QRect &trect, bool selected) const { if (auto reply = Get()) { - int32 h = st::msgReplyPadding.top() + st::msgReplyBarSize.height() + st::msgReplyPadding.bottom(); + int32_t h = st::msgReplyPadding.top() + st::msgReplyBarSize.height() + st::msgReplyPadding.bottom(); auto flags = HistoryMessageReply::PaintFlag::InBubble | 0; if (selected) { @@ -2173,7 +2173,7 @@ bool HistoryMessage::getStateForwardedInfo(QPoint point, QRect &trect, HistoryTe bool HistoryMessage::getStateReplyInfo(QPoint point, QRect &trect, HistoryTextState *outResult) const { if (auto reply = Get()) { - int32 h = st::msgReplyPadding.top() + st::msgReplyBarSize.height() + st::msgReplyPadding.bottom(); + int32_t h = st::msgReplyPadding.top() + st::msgReplyBarSize.height() + st::msgReplyPadding.bottom(); if (point.y() >= trect.top() && point.y() < trect.top() + h) { if (reply->replyToMsg && QRect(trect.x(), trect.y() + st::msgReplyPadding.top(), trect.width(), st::msgReplyBarSize.height()).contains(point)) { outResult->link = reply->replyToLink(); diff --git a/Telegram/SourceFiles/history/history_message.h b/Telegram/SourceFiles/history/history_message.h index 39fafd0bd..4e08e6dd1 100644 --- a/Telegram/SourceFiles/history/history_message.h +++ b/Telegram/SourceFiles/history/history_message.h @@ -53,9 +53,9 @@ public: void initTime(); void initMedia(const MTPMessageMedia *media); void initMediaFromDocument(DocumentData *doc, const QString &caption); - void fromNameUpdated(int32 width) const; + void fromNameUpdated(int32_t width) const; - int32 plainMaxWidth() const; + int32_t plainMaxWidth() const; QRect countGeometry() const; bool drawBubble() const; @@ -71,9 +71,9 @@ public: bool uploading() const; bool displayFastShare() const override; - void drawInfo(Painter &p, int32 right, int32 bottom, int32 width, bool selected, InfoDisplayType type) const override; + void drawInfo(Painter &p, int32_t right, int32_t bottom, int32_t width, bool selected, InfoDisplayType type) const override; void drawFastShare(Painter &p, int left, int top, int outerWidth) const override; - void setViewsCount(int32 count) override; + void setViewsCount(int32_t count) override; void setId(MsgId newId) override; void draw(Painter &p, QRect clip, TextSelection selection, TimeMs ms) const override; ClickHandlerPtr fastShareLink() const override; @@ -100,7 +100,7 @@ public: void updateReplyMarkup(const MTPReplyMarkup *markup) override { setReplyMarkup(markup); } - int32 addToOverview(AddToOverviewMethod method) override; + int32_t addToOverview(AddToOverviewMethod method) override; void eraseFromOverview() override; TextWithEntities selectedText(TextSelection selection) const override; @@ -219,7 +219,7 @@ private: void repaint(not_null item) const override; protected: - void paintButtonBg(Painter &p, const QRect &rect, float64 howMuchOver) const override; + void paintButtonBg(Painter &p, const QRect &rect, double howMuchOver) const override; void paintButtonIcon(Painter &p, const QRect &rect, int outerWidth, HistoryMessageReplyMarkup::Button::Type type) const override; void paintButtonLoading(Painter &p, const QRect &rect) const override; int minButtonWidth(HistoryMessageReplyMarkup::Button::Type type) const override; diff --git a/Telegram/SourceFiles/history/history_service.cpp b/Telegram/SourceFiles/history/history_service.cpp index 4d9e1c9e5..cdabe8bf5 100644 --- a/Telegram/SourceFiles/history/history_service.cpp +++ b/Telegram/SourceFiles/history/history_service.cpp @@ -410,7 +410,7 @@ HistoryService::HistoryService(not_null history, const MTPDmessageServ createFromMtp(message); } -HistoryService::HistoryService(not_null history, MsgId msgId, QDateTime date, const PreparedText &message, MTPDmessage::Flags flags, int32 from, PhotoData *photo) : +HistoryService::HistoryService(not_null history, MsgId msgId, QDateTime date, const PreparedText &message, MTPDmessage::Flags flags, int32_t from, PhotoData *photo) : HistoryItem(history, msgId, flags, date, from) { setServiceText(message); if (photo) { @@ -721,10 +721,10 @@ void HistoryService::removeMedia() { } } -int32 HistoryService::addToOverview(AddToOverviewMethod method) { +int32_t HistoryService::addToOverview(AddToOverviewMethod method) { if (!indexInOverview()) return 0; - int32 result = 0; + int32_t result = 0; if (auto media = getMedia()) { result |= media->addToOverview(method); } diff --git a/Telegram/SourceFiles/history/history_service.h b/Telegram/SourceFiles/history/history_service.h index 109a2b2d8..98efd7b28 100644 --- a/Telegram/SourceFiles/history/history_service.h +++ b/Telegram/SourceFiles/history/history_service.h @@ -98,7 +98,7 @@ public: void applyEdition(const MTPDmessageService &message) override; TimeMs getSelfDestructIn(TimeMs now) override; - int32 addToOverview(AddToOverviewMethod method) override; + int32_t addToOverview(AddToOverviewMethod method) override; void eraseFromOverview() override; bool needCheck() const override { diff --git a/Telegram/SourceFiles/history/history_service_layout.cpp b/Telegram/SourceFiles/history/history_service_layout.cpp index 7b7b28f5f..d0fdfcb89 100644 --- a/Telegram/SourceFiles/history/history_service_layout.cpp +++ b/Telegram/SourceFiles/history/history_service_layout.cpp @@ -206,7 +206,7 @@ void ServiceMessagePainter::paint( auto skiptop = top - fill; auto fillheight = fill + height + fill; - auto dt = (animms > st::activeFadeInDuration) ? (1. - (animms - st::activeFadeInDuration) / float64(st::activeFadeOutDuration)) : (animms / float64(st::activeFadeInDuration)); + auto dt = (animms > st::activeFadeInDuration) ? (1. - (animms - st::activeFadeInDuration) / double(st::activeFadeOutDuration)) : (animms / double(st::activeFadeInDuration)); auto o = p.opacity(); p.setOpacity(o * dt); p.fillRect(0, skiptop, message->history()->width, fillheight, st::defaultTextPalette.selectOverlay); diff --git a/Telegram/SourceFiles/history/history_widget.cpp b/Telegram/SourceFiles/history/history_widget.cpp index e6e6056fc..260d63c25 100644 --- a/Telegram/SourceFiles/history/history_widget.cpp +++ b/Telegram/SourceFiles/history/history_widget.cpp @@ -195,7 +195,7 @@ ApiWrap::RequestMessageDataCallback replyEditMessageDataCallback() { MTPVector composeDocumentAttributes(DocumentData *document) { QVector attributes(1, MTP_documentAttributeFilename(MTP_string(document->name))); if (document->dimensions.width() > 0 && document->dimensions.height() > 0) { - int32 duration = document->duration(); + int32_t duration = document->duration(); if (duration >= 0) { auto flags = MTPDdocumentAttributeVideo::Flags(0); if (document->isRoundVideo()) { @@ -666,8 +666,8 @@ HistoryWidget::HistoryWidget(QWidget *parent, not_null cont connect(&_sendActionStopTimer, SIGNAL(timeout()), this, SLOT(onCancelSendAction())); connect(&_previewTimer, SIGNAL(timeout()), this, SLOT(onPreviewTimeout())); connect(Media::Capture::instance(), SIGNAL(error()), this, SLOT(onRecordError())); - connect(Media::Capture::instance(), SIGNAL(updated(quint16,qint32)), this, SLOT(onRecordUpdate(quint16,qint32))); - connect(Media::Capture::instance(), SIGNAL(done(QByteArray,VoiceWaveform,qint32)), this, SLOT(onRecordDone(QByteArray,VoiceWaveform,qint32))); + connect(Media::Capture::instance(), SIGNAL(updated(uint16_t,int32_t)), this, SLOT(onRecordUpdate(uint16_t,int32_t))); + connect(Media::Capture::instance(), SIGNAL(done(QByteArray,VoiceWaveform,int32_t)), this, SLOT(onRecordDone(QByteArray,VoiceWaveform,int32_t))); _attachToggle->setClickedCallback(App::LambdaDelayed(st::historyAttach.ripple.hideDuration, this, [this] { chooseAttach(); @@ -1350,7 +1350,7 @@ void HistoryWidget::onCancelSendAction() { cancelSendAction(_history, SendAction::Type::Typing); } -void HistoryWidget::updateSendAction(History *history, SendAction::Type type, int32 progress) { +void HistoryWidget::updateSendAction(History *history, SendAction::Type type, int32_t progress) { if (!history) return; auto doing = (progress >= 0); @@ -1383,7 +1383,7 @@ void HistoryWidget::updateRecentStickers() { _tabbedSelector->refreshStickers(); } -void HistoryWidget::stickersInstalled(uint64 setId) { +void HistoryWidget::stickersInstalled(uint64_t setId) { if (_tabbedPanel) { _tabbedPanel->stickersInstalled(setId); } else if (_tabbedSection) { @@ -1427,7 +1427,7 @@ void HistoryWidget::onRecordError() { stopRecording(false); } -void HistoryWidget::onRecordDone(QByteArray result, VoiceWaveform waveform, qint32 samples) { +void HistoryWidget::onRecordDone(QByteArray result, VoiceWaveform waveform, int32_t samples) { if (!canWriteMessage() || result.isEmpty()) return; App::wnd()->activateWindow(); @@ -1438,7 +1438,7 @@ void HistoryWidget::onRecordDone(QByteArray result, VoiceWaveform waveform, qint cancelReplyAfterMediaSend(lastForceReplyReplied()); } -void HistoryWidget::onRecordUpdate(quint16 level, qint32 samples) { +void HistoryWidget::onRecordUpdate(uint16_t level, int32_t samples) { if (!_recording) { return; } @@ -2378,7 +2378,7 @@ void HistoryWidget::messagesReceived(PeerData *peer, const MTPmessages_Messages return; } - int32 count = 0; + int32_t count = 0; const QVector emptyList, *histList = &emptyList; switch (messages.type()) { case mtpc_messages_messages: { @@ -2935,7 +2935,7 @@ void HistoryWidget::onBotStart() { if (token.isEmpty()) { sendBotCommand(_peer, _peer->asUser(), qsl("/start"), 0); } else { - uint64 randomId = rand_value(); + uint64_t randomId = rand_value(); MTP::send(MTPmessages_StartBot(_peer->asUser()->inputUser, MTP_inputPeerEmpty(), MTP_long(randomId), MTP_string(token)), App::main()->rpcDone(&MainWidget::sentUpdatesReceived), App::main()->rpcFail(&MainWidget::addParticipantFail, { _peer->asUser(), (PeerData*)nullptr })); _peer->asUser()->botInfo->startToken = QString(); @@ -2998,10 +2998,10 @@ void HistoryWidget::onShareContact(const PeerId &peer, UserData *contact) { shareContact(peer, phone, contact->firstName, contact->lastName, replyToId(), peerToUser(contact->id)); } -void HistoryWidget::shareContact(const PeerId &peer, const QString &phone, const QString &fname, const QString &lname, MsgId replyTo, int32 userId) { +void HistoryWidget::shareContact(const PeerId &peer, const QString &phone, const QString &fname, const QString &lname, MsgId replyTo, int32_t userId) { auto history = App::history(peer); - uint64 randomId = rand_value(); + uint64_t randomId = rand_value(); FullMsgId newId(peerToChannel(peer), clientMsgId()); App::main()->readServerHistory(history); @@ -3148,8 +3148,8 @@ void HistoryWidget::unreadMentionsAnimationFinish() { updateUnreadMentionsPosition(); } -void HistoryWidget::step_recording(float64 ms, bool timer) { - float64 dt = ms / AudioVoiceMsgUpdateView; +void HistoryWidget::step_recording(double ms, bool timer) { + double dt = ms / AudioVoiceMsgUpdateView; if (dt >= 1) { _a_recording.stop(); a_recordingLevel.finish(); @@ -3334,7 +3334,7 @@ void HistoryWidget::sendBotCommand(PeerData *peer, UserData *bot, const QString bot = nullptr; } QString username = bot ? bot->asUser()->username : QString(); - int32 botStatus = _peer->isChat() ? _peer->asChat()->botStatus : (_peer->isMegagroup() ? _peer->asChannel()->mgInfo->botStatus : -1); + int32_t botStatus = _peer->isChat() ? _peer->asChat()->botStatus : (_peer->isMegagroup() ? _peer->asChannel()->mgInfo->botStatus : -1); if (!replyTo && toSend.indexOf('@') < 2 && !username.isEmpty() && (botStatus == 0 || botStatus == 2)) { toSend += '@' + username; } @@ -3548,7 +3548,7 @@ DragState HistoryWidget::getDragState(const QMimeData *d) { QFileInfo info(file); if (info.isDir()) return DragStateNone; - quint64 s = info.size(); + uint64_t s = info.size(); if (s > App::kFileSizeLimit) { return DragStateNone; } @@ -3777,7 +3777,7 @@ void HistoryWidget::onKbToggle(bool manual) { _kbScroll->show(); _kbShown = true; - int32 maxh = qMin(_keyboard->height(), st::historyComposeFieldMaxHeight - (st::historyComposeFieldMaxHeight / 2)); + int32_t maxh = qMin(_keyboard->height(), st::historyComposeFieldMaxHeight - (st::historyComposeFieldMaxHeight / 2)); _field->setMaxHeight(st::historyComposeFieldMaxHeight - maxh); _kbReplyTo = (_peer->isChat() || _peer->isChannel() || _keyboard->forceReply()) ? App::histItemById(_keyboard->forMsgId()) : 0; @@ -4005,7 +4005,7 @@ void HistoryWidget::updateOnlineDisplay() { if (!_history) return; QString text; - int32 t = unixtime(); + int32_t t = unixtime(); bool titlePeerTextOnline = false; if (auto user = _peer->asUser()) { text = App::onlineText(user, t); @@ -4084,7 +4084,7 @@ void HistoryWidget::updateOnlineDisplay() { void HistoryWidget::updateOnlineDisplayTimer() { if (!_history) return; - int32 t = unixtime(), minIn = 86400; + int32_t t = unixtime(), minIn = 86400; if (_peer->isUser()) { minIn = App::onlineWillChangeIn(_peer->asUser(), t); } else if (_peer->isChat()) { @@ -4092,7 +4092,7 @@ void HistoryWidget::updateOnlineDisplayTimer() { if (chat->participants.isEmpty()) return; for (auto i = chat->participants.cbegin(), e = chat->participants.cend(); i != e; ++i) { - int32 onlineWillChangeIn = App::onlineWillChangeIn(i.key(), t); + int32_t onlineWillChangeIn = App::onlineWillChangeIn(i.key(), t); if (onlineWillChangeIn < minIn) { minIn = onlineWillChangeIn; } @@ -4524,7 +4524,7 @@ void HistoryWidget::sendFileConfirmed(const FileLoadResultPtr &file) { void HistoryWidget::onPhotoUploaded(const FullMsgId &newId, bool silent, const MTPInputFile &file) { if (auto item = App::histItemById(newId)) { - uint64 randomId = rand_value(); + uint64_t randomId = rand_value(); App::historyRegRandom(randomId, newId); History *hist = item->history(); MsgId replyTo = item->replyToId(); @@ -4548,7 +4548,7 @@ void HistoryWidget::onDocumentUploaded(const FullMsgId &newId, bool silent, cons if (auto item = dynamic_cast(App::histItemById(newId))) { auto media = item->getMedia(); if (auto document = media ? media->getDocument() : nullptr) { - auto randomId = rand_value(); + auto randomId = rand_value(); App::historyRegRandom(randomId, newId); auto hist = item->history(); auto replyTo = item->replyToId(); @@ -4573,7 +4573,7 @@ void HistoryWidget::onThumbDocumentUploaded(const FullMsgId &newId, bool silent, if (auto item = dynamic_cast(App::histItemById(newId))) { auto media = item->getMedia(); if (auto document = media ? media->getDocument() : nullptr) { - auto randomId = rand_value(); + auto randomId = rand_value(); App::historyRegRandom(randomId, newId); auto hist = item->history(); auto replyTo = item->replyToId(); @@ -5117,7 +5117,7 @@ void HistoryWidget::updateBotKeyboard(History *h, bool force) { _botKeyboardShow->hide(); _botCommandStart->hide(); } - int32 maxh = hasMarkup ? qMin(_keyboard->height(), st::historyComposeFieldMaxHeight - (st::historyComposeFieldMaxHeight / 2)) : 0; + int32_t maxh = hasMarkup ? qMin(_keyboard->height(), st::historyComposeFieldMaxHeight - (st::historyComposeFieldMaxHeight / 2)) : 0; _field->setMaxHeight(st::historyComposeFieldMaxHeight - maxh); _kbShown = hasMarkup; _kbReplyTo = (_peer->isChat() || _peer->isChannel() || _keyboard->forceReply()) ? App::histItemById(_keyboard->forMsgId()) : 0; @@ -5333,7 +5333,7 @@ void HistoryWidget::onInlineResultSend(InlineBots::Result *result, UserData *bot App::main()->readServerHistory(_history); fastShowAtEnd(_history); - uint64 randomId = rand_value(); + uint64_t randomId = rand_value(); FullMsgId newId(_channel, clientMsgId()); bool lastKeyboardUsed = lastForceReplyReplied(); @@ -5383,7 +5383,7 @@ void HistoryWidget::onInlineResultSend(InlineBots::Result *result, UserData *bot onDraftSave(); RecentInlineBots &bots(cRefRecentInlineBots()); - int32 index = bots.indexOf(bot); + int32_t index = bots.indexOf(bot); if (index) { if (index > 0) { bots.removeAt(index); @@ -5508,7 +5508,7 @@ bool HistoryWidget::sendExistingDocument(DocumentData *doc, const QString &capti App::main()->readServerHistory(_history); fastShowAtEnd(_history); - uint64 randomId = rand_value(); + uint64_t randomId = rand_value(); FullMsgId newId(_channel, clientMsgId()); bool lastKeyboardUsed = lastForceReplyReplied(); @@ -5566,7 +5566,7 @@ void HistoryWidget::sendExistingPhoto(PhotoData *photo, const QString &caption) App::main()->readServerHistory(_history); fastShowAtEnd(_history); - uint64 randomId = rand_value(); + uint64_t randomId = rand_value(); FullMsgId newId(_channel, clientMsgId()); bool lastKeyboardUsed = lastForceReplyReplied(); @@ -6005,7 +6005,7 @@ void HistoryWidget::updatePreview() { #endif // OS_MAC_OLD _previewDescription.setText(st::messageTextStyle, TextUtilities::Clean(linkText), _textDlgOptions); - int32 t = (_previewData->pendingTill - unixtime()) * 1000; + int32_t t = (_previewData->pendingTill - unixtime()) * 1000; if (t <= 0) t = 1; _previewTimer.start(t); } else { @@ -6303,7 +6303,7 @@ void HistoryWidget::updateForwarding() { } void HistoryWidget::updateForwardingTexts() { - int32 version = 0; + int32_t version = 0; QString from, text; if (!_toForward.isEmpty()) { QMap fromUsersMap; @@ -6500,7 +6500,7 @@ void HistoryWidget::paintEditHeader(Painter &p, const QRect &rect, int left, int if (editTimeLeft < 2) { editTimeLeftText = qsl("0:00"); } else if (editTimeLeft > kDisplayEditTimeWarningMs) { - updateIn = static_cast(qMin(editTimeLeft - kDisplayEditTimeWarningMs, qint64(kFullDayInMs))); + updateIn = static_cast(qMin(editTimeLeft - kDisplayEditTimeWarningMs, int64_t(kFullDayInMs))); } else { updateIn = static_cast(editTimeLeft % 1000); if (!updateIn) { @@ -6524,7 +6524,7 @@ void HistoryWidget::paintEditHeader(Painter &p, const QRect &rect, int left, int } } -void HistoryWidget::drawRecording(Painter &p, float64 recordActive) { +void HistoryWidget::drawRecording(Painter &p, double recordActive) { p.setPen(Qt::NoPen); p.setBrush(st::historyRecordSignalColor); @@ -6541,8 +6541,8 @@ void HistoryWidget::drawRecording(Painter &p, float64 recordActive) { p.setPen(st::historyRecordDurationFg); p.drawText(_attachToggle->x() + _tabbedSelectorToggle->width(), _attachToggle->y() + st::historyRecordTextTop + st::historyRecordFont->ascent, duration); - int32 left = _attachToggle->x() + _tabbedSelectorToggle->width() + st::historyRecordFont->width(duration) + ((_send->width() - st::historyRecordVoice.width()) / 2); - int32 right = _chatWidth - _send->width(); + int32_t left = _attachToggle->x() + _tabbedSelectorToggle->width() + st::historyRecordFont->width(duration) + ((_send->width() - st::historyRecordVoice.width()) / 2); + int32_t right = _chatWidth - _send->width(); p.setPen(anim::pen(st::historyRecordCancel, st::historyRecordCancelActive, 1. - recordActive)); p.drawText(left + (right - left - _recordCancelWidth) / 2, _attachToggle->y() + st::historyRecordTextTop + st::historyRecordFont->ascent, lang(lng_record_cancel)); @@ -6561,7 +6561,7 @@ void HistoryWidget::drawPinnedBar(Painter &p) { QRect rbar(myrtlrect(st::msgReplyBarSkip + st::msgReplyBarPos.x(), top + st::msgReplyBarPos.y(), st::msgReplyBarSize.width(), st::msgReplyBarSize.height())); p.fillRect(rbar, st::msgInReplyBarColor); - int32 left = st::msgReplyBarSkip + st::msgReplyBarSkip; + int32_t left = st::msgReplyBarSkip + st::msgReplyBarSkip; if (_pinnedBar->msg) { if (_pinnedBar->msg->getMedia() && _pinnedBar->msg->getMedia()->hasReplyPreview()) { ImagePtr replyPreview = _pinnedBar->msg->getMedia()->replyPreview(); @@ -6674,7 +6674,7 @@ void HistoryWidget::paintEvent(QPaintEvent *e) { } } else { style::font font(st::msgServiceFont); - int32 w = font->width(lang(lng_willbe_history)) + st::msgPadding.left() + st::msgPadding.right(), h = font->height + st::msgServicePadding.top() + st::msgServicePadding.bottom() + 2; + int32_t w = font->width(lang(lng_willbe_history)) + st::msgPadding.left() + st::msgPadding.right(), h = font->height + st::msgServicePadding.top() + st::msgServicePadding.bottom() + 2; QRect tr((width() - w) / 2, (height() - _field->height() - 2 * st::historySendPadding - h) / 2, w, h); HistoryLayout::ServiceMessagePainter::paintBubble(p, tr.x(), tr.y(), tr.width(), tr.height()); @@ -6707,7 +6707,7 @@ QPoint HistoryWidget::clampMousePosition(QPoint point) { } void HistoryWidget::onScrollTimer() { - auto d = (_scrollDelta > 0) ? qMin(_scrollDelta * 3 / 20 + 1, int32(MaxScrollSpeed)) : qMax(_scrollDelta * 3 / 20 - 1, -int32(MaxScrollSpeed)); + auto d = (_scrollDelta > 0) ? qMin(_scrollDelta * 3 / 20 + 1, int32_t(MaxScrollSpeed)) : qMax(_scrollDelta * 3 / 20 - 1, -int32_t(MaxScrollSpeed)); _scroll->scrollToY(_scroll->scrollTop() + d); } @@ -6731,7 +6731,7 @@ void HistoryWidget::noSelectingScroll() { } bool HistoryWidget::touchScroll(const QPoint &delta) { - int32 scTop = _scroll->scrollTop(), scMax = _scroll->scrollTopMax(), scNew = snap(scTop - delta.y(), 0, scMax); + int32_t scTop = _scroll->scrollTop(), scMax = _scroll->scrollTopMax(), scNew = snap(scTop - delta.y(), 0, scMax); if (scNew == scTop) return false; _scroll->scrollToY(scNew); diff --git a/Telegram/SourceFiles/history/history_widget.h b/Telegram/SourceFiles/history/history_widget.h index cd06a8ead..cbfab4a30 100644 --- a/Telegram/SourceFiles/history/history_widget.h +++ b/Telegram/SourceFiles/history/history_widget.h @@ -162,7 +162,7 @@ private: int _chooseWidth = 0; Text _toText; - int32 _toTextWidth = 0; + int32_t _toTextWidth = 0; QPixmap _cacheForAnim; }; @@ -211,11 +211,11 @@ public: int minimalWidthForTabbedSelectorSection() const; bool willSwitchToTabbedSelectorWithWidth(int newWidth) const; - void updateSendAction(History *history, SendAction::Type type, int32 progress = 0); + void updateSendAction(History *history, SendAction::Type type, int32_t progress = 0); void cancelSendAction(History *history, SendAction::Type type); void updateRecentStickers(); - void stickersInstalled(uint64 setId); + void stickersInstalled(uint64_t setId); void sendActionDone(const MTPBool &result, mtpRequestId req); void destroyData(); @@ -241,7 +241,7 @@ public: void onShareContact(const PeerId &peer, UserData *contact); - void shareContact(const PeerId &peer, const QString &phone, const QString &fname, const QString &lname, MsgId replyTo, int32 userId = 0); + void shareContact(const PeerId &peer, const QString &phone, const QString &fname, const QString &lname, MsgId replyTo, int32_t userId = 0); History *history() const; PeerData *peer() const; @@ -289,7 +289,7 @@ public: void updatePreview(); void previewCancel(); - void step_recording(float64 ms, bool timer); + void step_recording(double ms, bool timer); void stopRecording(bool send); void onListEscapePressed(); @@ -451,8 +451,8 @@ public slots: void onCloudDraftSave(); void onRecordError(); - void onRecordDone(QByteArray result, VoiceWaveform waveform, qint32 samples); - void onRecordUpdate(quint16 level, qint32 samples); + void onRecordDone(QByteArray result, VoiceWaveform waveform, int32_t samples); + void onRecordUpdate(uint16_t level, int32_t samples); void onUpdateHistoryItems(); @@ -593,7 +593,7 @@ private: void drawField(Painter &p, const QRect &rect); void paintEditHeader(Painter &p, const QRect &rect, int left, int top) const; - void drawRecording(Painter &p, float64 recordActive); + void drawRecording(Painter &p, double recordActive); void drawPinnedBar(Painter &p); void drawRestrictedWrite(Painter &p); @@ -836,7 +836,7 @@ private: TaskQueue _fileLoader; TextUpdateEvents _textUpdateEvents = (TextUpdateEvents() | TextUpdateEvent::SaveDraft | TextUpdateEvent::SendTyping); - int64 _serviceImageCacheSize = 0; + int64_t _serviceImageCacheSize = 0; QString _confirmSource; QString _titlePeerText; @@ -848,7 +848,7 @@ private: QPixmap _cacheUnder, _cacheOver; QTimer _scrollTimer; - int32 _scrollDelta = 0; + int32_t _scrollDelta = 0; MsgId _highlightedMessageId = 0; std::deque _highlightQueue; diff --git a/Telegram/SourceFiles/inline_bots/inline_bot_layout_internal.cpp b/Telegram/SourceFiles/inline_bots/inline_bot_layout_internal.cpp index 078dad98d..e91cf31b0 100644 --- a/Telegram/SourceFiles/inline_bots/inline_bot_layout_internal.cpp +++ b/Telegram/SourceFiles/inline_bots/inline_bot_layout_internal.cpp @@ -104,17 +104,17 @@ Gif::Gif(not_null context, DocumentData *document, bool hasDeleteButto } void Gif::initDimensions() { - int32 w = content_width(), h = content_height(); + int32_t w = content_width(), h = content_height(); if (w <= 0 || h <= 0) { _maxw = 0; } else { w = w * st::inlineMediaHeight / h; - _maxw = qMax(w, int32(st::inlineResultsMinWidth)); + _maxw = qMax(w, int32_t(st::inlineResultsMinWidth)); } _minh = st::inlineMediaHeight + st::inlineResultsSkip; } -void Gif::setPosition(int32 position) { +void Gif::setPosition(int32_t position) { ItemBase::setPosition(position); if (_position < 0) { _gif.reset(); @@ -154,7 +154,7 @@ void Gif::paint(Painter &p, const QRect &clip, const PaintContext *context) cons } bool radial = isRadialAnimation(context->ms); - int32 height = st::inlineMediaHeight; + int32_t height = st::inlineMediaHeight; QSize frame = countFrameSize(); QRect r(0, 0, _width, height); @@ -256,14 +256,14 @@ void Gif::clickHandlerActiveChanged(const ClickHandlerPtr &p, bool active) { QSize Gif::countFrameSize() const { bool animating = (_gif && _gif->ready()); - int32 framew = animating ? _gif->width() : content_width(), frameh = animating ? _gif->height() : content_height(), height = st::inlineMediaHeight; + int32_t framew = animating ? _gif->width() : content_width(), frameh = animating ? _gif->height() : content_height(), height = st::inlineMediaHeight; if (framew * height > frameh * _width) { if (framew < st::maxStickerSize || frameh > height) { if (frameh > height || (framew * height / frameh) <= st::maxStickerSize) { framew = framew * height / frameh; frameh = height; } else { - frameh = int32(frameh * st::maxStickerSize) / framew; + frameh = int32_t(frameh * st::maxStickerSize) / framew; framew = st::maxStickerSize; } } @@ -273,7 +273,7 @@ QSize Gif::countFrameSize() const { frameh = frameh * _width / framew; framew = _width; } else { - framew = int32(framew * st::maxStickerSize) / frameh; + framew = int32_t(framew * st::maxStickerSize) / frameh; frameh = st::maxStickerSize; } } @@ -281,7 +281,7 @@ QSize Gif::countFrameSize() const { return QSize(framew, frameh); } -void Gif::prepareThumb(int32 width, int32 height, const QSize &frame) const { +void Gif::prepareThumb(int32_t width, int32_t height, const QSize &frame) const { if (DocumentData *document = getShownDocument()) { if (!document->thumb->isNull()) { if (document->thumb->loaded()) { @@ -424,9 +424,9 @@ void Sticker::clickHandlerActiveChanged(const ClickHandlerPtr &p, bool active) { QSize Sticker::getThumbSize() const { int width = qMax(content_width(), 1), height = qMax(content_height(), 1); - float64 coefw = (st::stickerPanSize.width() - st::buttonRadius * 2) / float64(width); - float64 coefh = (st::stickerPanSize.height() - st::buttonRadius * 2) / float64(height); - float64 coef = qMin(qMin(coefw, coefh), 1.); + double coefw = (st::stickerPanSize.width() - st::buttonRadius * 2) / double(width); + double coefh = (st::stickerPanSize.height() - st::buttonRadius * 2) / double(height); + double coef = qMin(qMin(coefw, coefh), 1.); int w = qRound(coef * content_width()), h = qRound(coef * content_height()); return QSize(qMax(w, 1), qMax(h, 1)); } @@ -465,18 +465,18 @@ Photo::Photo(not_null context, Result *result) : ItemBase(context, res void Photo::initDimensions() { PhotoData *photo = getShownPhoto(); - int32 w = photo->full->width(), h = photo->full->height(); + int32_t w = photo->full->width(), h = photo->full->height(); if (w <= 0 || h <= 0) { _maxw = 0; } else { w = w * st::inlineMediaHeight / h; - _maxw = qMax(w, int32(st::inlineResultsMinWidth)); + _maxw = qMax(w, int32_t(st::inlineResultsMinWidth)); } _minh = st::inlineMediaHeight + st::inlineResultsSkip; } void Photo::paint(Painter &p, const QRect &clip, const PaintContext *context) const { - int32 height = st::inlineMediaHeight; + int32_t height = st::inlineMediaHeight; QSize frame = countFrameSize(); QRect r(0, 0, _width, height); @@ -504,14 +504,14 @@ PhotoData *Photo::getShownPhoto() const { QSize Photo::countFrameSize() const { PhotoData *photo = getShownPhoto(); - int32 framew = photo->full->width(), frameh = photo->full->height(), height = st::inlineMediaHeight; + int32_t framew = photo->full->width(), frameh = photo->full->height(), height = st::inlineMediaHeight; if (framew * height > frameh * _width) { if (framew < st::maxStickerSize || frameh > height) { if (frameh > height || (framew * height / frameh) <= st::maxStickerSize) { framew = framew * height / frameh; frameh = height; } else { - frameh = int32(frameh * st::maxStickerSize) / framew; + frameh = int32_t(frameh * st::maxStickerSize) / framew; framew = st::maxStickerSize; } } @@ -521,7 +521,7 @@ QSize Photo::countFrameSize() const { frameh = frameh * _width / framew; framew = _width; } else { - framew = int32(framew * st::maxStickerSize) / frameh; + framew = int32_t(framew * st::maxStickerSize) / frameh; frameh = st::maxStickerSize; } } @@ -529,7 +529,7 @@ QSize Photo::countFrameSize() const { return QSize(framew, frameh); } -void Photo::prepareThumb(int32 width, int32 height, const QSize &frame) const { +void Photo::prepareThumb(int32_t width, int32_t height, const QSize &frame) const { if (PhotoData *photo = getShownPhoto()) { if (photo->medium->loaded()) { if (!_thumbLoaded || _thumb.width() != width * cIntRetinaFactor() || _thumb.height() != height * cIntRetinaFactor()) { @@ -570,16 +570,16 @@ void Video::initDimensions() { bool withThumb = !content_thumb()->isNull(); _maxw = st::emojiPanWidth - st::emojiScroll.width - st::inlineResultsLeft; - int32 textWidth = _maxw - (withThumb ? (st::inlineThumbSize + st::inlineThumbSkip) : 0); + int32_t textWidth = _maxw - (withThumb ? (st::inlineThumbSize + st::inlineThumbSkip) : 0); TextParseOptions titleOpts = { 0, _maxw, 2 * st::semiboldFont->height, Qt::LayoutDirectionAuto }; auto title = TextUtilities::SingleLine(_result->getLayoutTitle()); if (title.isEmpty()) { title = lang(lng_media_video); } _title.setText(st::semiboldTextStyle, title, titleOpts); - int32 titleHeight = qMin(_title.countHeight(_maxw), 2 * st::semiboldFont->height); + int32_t titleHeight = qMin(_title.countHeight(_maxw), 2 * st::semiboldFont->height); - int32 descriptionLines = withThumb ? (titleHeight > st::semiboldFont->height ? 1 : 2) : 3; + int32_t descriptionLines = withThumb ? (titleHeight > st::semiboldFont->height ? 1 : 2) : 3; TextParseOptions descriptionOpts = { TextParseMultiline, _maxw, descriptionLines * st::normalFont->height, Qt::LayoutDirectionAuto }; QString description = _result->getLayoutDescription(); @@ -587,7 +587,7 @@ void Video::initDimensions() { description = _duration; } _description.setText(st::defaultTextStyle, description, descriptionOpts); - int32 descriptionHeight = qMin(_description.countHeight(_maxw), descriptionLines * st::normalFont->height); + int32_t descriptionHeight = qMin(_description.countHeight(_maxw), descriptionLines * st::normalFont->height); _minh = st::inlineThumbSize; _minh += st::inlineRowMargin * 2 + st::inlineRowBorder; @@ -620,10 +620,10 @@ void Video::paint(Painter &p, const QRect &clip, const PaintContext *context) co p.setPen(st::inlineTitleFg); _title.drawLeftElided(p, left, st::inlineRowMargin, _width - left, _width, 2); - int32 titleHeight = qMin(_title.countHeight(_width - left), st::semiboldFont->height * 2); + int32_t titleHeight = qMin(_title.countHeight(_width - left), st::semiboldFont->height * 2); p.setPen(st::inlineDescriptionFg); - int32 descriptionLines = withThumb ? (titleHeight > st::semiboldFont->height ? 1 : 2) : 3; + int32_t descriptionLines = withThumb ? (titleHeight > st::semiboldFont->height ? 1 : 2) : 3; _description.drawLeftElided(p, left, st::inlineRowMargin + titleHeight, _width - left, _width, descriptionLines); if (!context->lastRow) { @@ -642,11 +642,11 @@ void Video::getState(ClickHandlerPtr &link, HistoryCursorState &cursor, QPoint p } } -void Video::prepareThumb(int32 width, int32 height) const { +void Video::prepareThumb(int32_t width, int32_t height) const { ImagePtr thumb = content_thumb(); if (thumb->loaded()) { if (_thumb.width() != width * cIntRetinaFactor() || _thumb.height() != height * cIntRetinaFactor()) { - int32 w = qMax(convertScale(thumb->width()), 1), h = qMax(convertScale(thumb->height()), 1); + int32_t w = qMax(convertScale(thumb->width()), 1), h = qMax(convertScale(thumb->height()), 1); if (w * height > h * width) { if (height < h) { w = w * height / h; @@ -697,7 +697,7 @@ void File::initDimensions() { } void File::paint(Painter &p, const QRect &clip, const PaintContext *context) const { - int32 left = st::msgFileSize + st::inlineThumbSkip; + int32_t left = st::msgFileSize + st::inlineThumbSkip; DocumentData *document = getShownDocument(); bool loaded = document->loaded(), displayLoading = document->displayLoading(); @@ -826,7 +826,7 @@ void File::checkAnimationFinished() const { bool File::updateStatusText() const { bool showPause = false; - int32 statusSize = 0, realDuration = 0; + int32_t statusSize = 0, realDuration = 0; DocumentData *document = getShownDocument(); if (document->status == FileDownloadFailed || document->status == FileUploadFailed) { statusSize = FileStatusSizeFailed; @@ -862,13 +862,13 @@ bool File::updateStatusText() const { statusSize = FileStatusSizeReady; } if (statusSize != _statusSize) { - int32 duration = document->song() ? document->song()->duration : (document->voice() ? document->voice()->duration : -1); + int32_t duration = document->song() ? document->song()->duration : (document->voice() ? document->voice()->duration : -1); setStatusSize(statusSize, document->size, duration, realDuration); } return showPause; } -void File::setStatusSize(int32 newSize, int32 fullSize, int32 duration, qint64 realDuration) const { +void File::setStatusSize(int32_t newSize, int32_t fullSize, int32_t duration, int64_t realDuration) const { _statusSize = newSize; if (_statusSize == FileStatusSizeReady) { _statusText = (duration >= 0) ? formatDurationAndSizeText(duration, fullSize) : (duration < -1 ? formatGifAndSizeText(fullSize) : formatSizeText(fullSize)); @@ -890,27 +890,27 @@ Contact::Contact(not_null context, Result *result) : ItemBase(context, void Contact::initDimensions() { _maxw = st::emojiPanWidth - st::emojiScroll.width - st::inlineResultsLeft; - int32 textWidth = _maxw - (st::inlineThumbSize + st::inlineThumbSkip); + int32_t textWidth = _maxw - (st::inlineThumbSize + st::inlineThumbSkip); TextParseOptions titleOpts = { 0, _maxw, st::semiboldFont->height, Qt::LayoutDirectionAuto }; _title.setText(st::semiboldTextStyle, TextUtilities::SingleLine(_result->getLayoutTitle()), titleOpts); - int32 titleHeight = qMin(_title.countHeight(_maxw), st::semiboldFont->height); + int32_t titleHeight = qMin(_title.countHeight(_maxw), st::semiboldFont->height); TextParseOptions descriptionOpts = { TextParseMultiline, _maxw, st::normalFont->height, Qt::LayoutDirectionAuto }; _description.setText(st::defaultTextStyle, _result->getLayoutDescription(), descriptionOpts); - int32 descriptionHeight = qMin(_description.countHeight(_maxw), st::normalFont->height); + int32_t descriptionHeight = qMin(_description.countHeight(_maxw), st::normalFont->height); _minh = st::msgFileSize; _minh += st::inlineRowMargin * 2 + st::inlineRowBorder; } -int32 Contact::resizeGetHeight(int32 width) { +int32_t Contact::resizeGetHeight(int32_t width) { _width = qMin(width, _maxw); _height = _minh; return _height; } void Contact::paint(Painter &p, const QRect &clip, const PaintContext *context) const { - int32 left = st::emojiPanHeaderLeft - st::inlineResultsLeft; + int32_t left = st::emojiPanHeaderLeft - st::inlineResultsLeft; left = st::msgFileSize + st::inlineThumbSkip; prepareThumb(st::msgFileSize, st::msgFileSize); @@ -987,24 +987,24 @@ Article::Article(not_null context, Result *result, bool withThumb) : I void Article::initDimensions() { _maxw = st::emojiPanWidth - st::emojiScroll.width - st::inlineResultsLeft; - int32 textWidth = _maxw - (_withThumb ? (st::inlineThumbSize + st::inlineThumbSkip) : 0); + int32_t textWidth = _maxw - (_withThumb ? (st::inlineThumbSize + st::inlineThumbSkip) : 0); TextParseOptions titleOpts = { 0, _maxw, 2 * st::semiboldFont->height, Qt::LayoutDirectionAuto }; _title.setText(st::semiboldTextStyle, TextUtilities::SingleLine(_result->getLayoutTitle()), titleOpts); - int32 titleHeight = qMin(_title.countHeight(_maxw), 2 * st::semiboldFont->height); + int32_t titleHeight = qMin(_title.countHeight(_maxw), 2 * st::semiboldFont->height); - int32 descriptionLines = (_withThumb || _url) ? 2 : 3; + int32_t descriptionLines = (_withThumb || _url) ? 2 : 3; QString description = _result->getLayoutDescription(); TextParseOptions descriptionOpts = { TextParseMultiline, _maxw, descriptionLines * st::normalFont->height, Qt::LayoutDirectionAuto }; _description.setText(st::defaultTextStyle, description, descriptionOpts); - int32 descriptionHeight = qMin(_description.countHeight(_maxw), descriptionLines * st::normalFont->height); + int32_t descriptionHeight = qMin(_description.countHeight(_maxw), descriptionLines * st::normalFont->height); _minh = titleHeight + descriptionHeight; if (_url) _minh += st::normalFont->height; - if (_withThumb) _minh = qMax(_minh, int32(st::inlineThumbSize)); + if (_withThumb) _minh = qMax(_minh, int32_t(st::inlineThumbSize)); _minh += st::inlineRowMargin * 2 + st::inlineRowBorder; } -int32 Article::resizeGetHeight(int32 width) { +int32_t Article::resizeGetHeight(int32_t width) { _width = qMin(width, _maxw); if (_url) { _urlText = getResultUrl(); @@ -1019,7 +1019,7 @@ int32 Article::resizeGetHeight(int32 width) { } void Article::paint(Painter &p, const QRect &clip, const PaintContext *context) const { - int32 left = st::emojiPanHeaderLeft - st::inlineResultsLeft; + int32_t left = st::emojiPanHeaderLeft - st::inlineResultsLeft; if (_withThumb) { left = st::inlineThumbSize + st::inlineThumbSkip; prepareThumb(st::inlineThumbSize, st::inlineThumbSize); @@ -1027,7 +1027,7 @@ void Article::paint(Painter &p, const QRect &clip, const PaintContext *context) if (_thumb.isNull()) { ImagePtr thumb = getResultThumb(); if (thumb->isNull() && !_thumbLetter.isEmpty()) { - int32 index = (_thumbLetter.at(0).unicode() % 4); + int32_t index = (_thumbLetter.at(0).unicode() % 4); style::color colors[] = { st::msgFile3Bg, st::msgFile4Bg, @@ -1051,14 +1051,14 @@ void Article::paint(Painter &p, const QRect &clip, const PaintContext *context) p.setPen(st::inlineTitleFg); _title.drawLeftElided(p, left, st::inlineRowMargin, _width - left, _width, 2); - int32 titleHeight = qMin(_title.countHeight(_width - left), st::semiboldFont->height * 2); + int32_t titleHeight = qMin(_title.countHeight(_width - left), st::semiboldFont->height * 2); p.setPen(st::inlineDescriptionFg); - int32 descriptionLines = (_withThumb || _url) ? 2 : 3; + int32_t descriptionLines = (_withThumb || _url) ? 2 : 3; _description.drawLeftElided(p, left, st::inlineRowMargin + titleHeight, _width - left, _width, descriptionLines); if (_url) { - int32 descriptionHeight = qMin(_description.countHeight(_width - left), st::normalFont->height * descriptionLines); + int32_t descriptionHeight = qMin(_description.countHeight(_width - left), st::normalFont->height * descriptionLines); p.drawTextLeft(left, st::inlineRowMargin + titleHeight + descriptionHeight, _width, _urlText, _urlWidth); } @@ -1155,23 +1155,23 @@ void Game::countFrameSize() { void Game::initDimensions() { _maxw = st::emojiPanWidth - st::emojiScroll.width - st::inlineResultsLeft; - int32 textWidth = _maxw - (st::inlineThumbSize + st::inlineThumbSkip); + int32_t textWidth = _maxw - (st::inlineThumbSize + st::inlineThumbSkip); TextParseOptions titleOpts = { 0, _maxw, 2 * st::semiboldFont->height, Qt::LayoutDirectionAuto }; _title.setText(st::semiboldTextStyle, TextUtilities::SingleLine(_result->getLayoutTitle()), titleOpts); - int32 titleHeight = qMin(_title.countHeight(_maxw), 2 * st::semiboldFont->height); + int32_t titleHeight = qMin(_title.countHeight(_maxw), 2 * st::semiboldFont->height); - int32 descriptionLines = 2; + int32_t descriptionLines = 2; QString description = _result->getLayoutDescription(); TextParseOptions descriptionOpts = { TextParseMultiline, _maxw, descriptionLines * st::normalFont->height, Qt::LayoutDirectionAuto }; _description.setText(st::defaultTextStyle, description, descriptionOpts); - int32 descriptionHeight = qMin(_description.countHeight(_maxw), descriptionLines * st::normalFont->height); + int32_t descriptionHeight = qMin(_description.countHeight(_maxw), descriptionLines * st::normalFont->height); _minh = titleHeight + descriptionHeight; accumulate_max(_minh, st::inlineThumbSize); _minh += st::inlineRowMargin * 2 + st::inlineRowBorder; } -void Game::setPosition(int32 position) { +void Game::setPosition(int32_t position) { ItemBase::setPosition(position); if (_position < 0) { _gif.reset(); @@ -1179,7 +1179,7 @@ void Game::setPosition(int32 position) { } void Game::paint(Painter &p, const QRect &clip, const PaintContext *context) const { - int32 left = st::emojiPanHeaderLeft - st::inlineResultsLeft; + int32_t left = st::emojiPanHeaderLeft - st::inlineResultsLeft; left = st::inlineThumbSize + st::inlineThumbSkip; auto rthumb = rtlrect(0, st::inlineRowMargin, st::inlineThumbSize, st::inlineThumbSize, _width); @@ -1240,10 +1240,10 @@ void Game::paint(Painter &p, const QRect &clip, const PaintContext *context) con p.setPen(st::inlineTitleFg); _title.drawLeftElided(p, left, st::inlineRowMargin, _width - left, _width, 2); - int32 titleHeight = qMin(_title.countHeight(_width - left), st::semiboldFont->height * 2); + int32_t titleHeight = qMin(_title.countHeight(_width - left), st::semiboldFont->height * 2); p.setPen(st::inlineDescriptionFg); - int32 descriptionLines = 2; + int32_t descriptionLines = 2; _description.drawLeftElided(p, left, st::inlineRowMargin + titleHeight, _width - left, _width, descriptionLines); if (!context->lastRow) { diff --git a/Telegram/SourceFiles/inline_bots/inline_bot_layout_internal.h b/Telegram/SourceFiles/inline_bots/inline_bot_layout_internal.h index db578e338..f28ac3493 100644 --- a/Telegram/SourceFiles/inline_bots/inline_bot_layout_internal.h +++ b/Telegram/SourceFiles/inline_bots/inline_bot_layout_internal.h @@ -62,7 +62,7 @@ public: Gif(not_null context, Result *result); Gif(not_null context, DocumentData *doc, bool hasDeleteButton); - void setPosition(int32 position) override; + void setPosition(int32_t position) override; void initDimensions() override; bool isFullLine() const override { @@ -92,7 +92,7 @@ private: Media::Clip::ReaderPointer _gif; ClickHandlerPtr _delete; mutable QPixmap _thumb; - void prepareThumb(int32 width, int32 height, const QSize &frame) const; + void prepareThumb(int32_t width, int32_t height, const QSize &frame) const; void ensureAnimation() const; bool isRadialAnimation(TimeMs ms) const; @@ -139,7 +139,7 @@ private: mutable QPixmap _thumb; mutable bool _thumbLoaded = false; - void prepareThumb(int32 width, int32 height, const QSize &frame) const; + void prepareThumb(int32_t width, int32_t height, const QSize &frame) const; }; @@ -194,7 +194,7 @@ private: QString _duration; int _durationWidth = 0; - void prepareThumb(int32 width, int32 height) const; + void prepareThumb(int32_t width, int32_t height) const; }; @@ -278,11 +278,11 @@ private: // 0x7FFFFFF0 will contain status for not yet downloaded file // 0x7FFFFFF1 will contain status for already downloaded file // 0x7FFFFFF2 will contain status for failed to download / upload file - mutable int32 _statusSize; + mutable int32_t _statusSize; mutable QString _statusText; // duration = -1 - no duration, duration = -2 - "GIF" duration - void setStatusSize(int32 newSize, int32 fullSize, int32 duration, qint64 realDuration) const; + void setStatusSize(int32_t newSize, int32_t fullSize, int32_t duration, int64_t realDuration) const; }; @@ -321,7 +321,7 @@ private: mutable QPixmap _thumb; Text _title, _description; QString _thumbLetter, _urlText; - int32 _urlWidth; + int32_t _urlWidth; void prepareThumb(int width, int height) const; @@ -331,7 +331,7 @@ class Game : public ItemBase { public: Game(not_null context, Result *result); - void setPosition(int32 position) override; + void setPosition(int32_t position) override; void initDimensions() override; void paint(Painter &p, const QRect &clip, const PaintContext *context) const override; @@ -340,7 +340,7 @@ public: private: void countFrameSize(); - void prepareThumb(int32 width, int32 height) const; + void prepareThumb(int32_t width, int32_t height) const; bool isRadialAnimation(TimeMs ms) const; void step_radial(TimeMs ms, bool timer); diff --git a/Telegram/SourceFiles/inline_bots/inline_bot_layout_item.cpp b/Telegram/SourceFiles/inline_bots/inline_bot_layout_item.cpp index 3ae0e1da3..99223ea25 100644 --- a/Telegram/SourceFiles/inline_bots/inline_bot_layout_item.cpp +++ b/Telegram/SourceFiles/inline_bots/inline_bot_layout_item.cpp @@ -29,11 +29,11 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org namespace InlineBots { namespace Layout { -void ItemBase::setPosition(int32 position) { +void ItemBase::setPosition(int32_t position) { _position = position; } -int32 ItemBase::position() const { +int32_t ItemBase::position() const { return _position; } diff --git a/Telegram/SourceFiles/inline_bots/inline_bot_layout_item.h b/Telegram/SourceFiles/inline_bots/inline_bot_layout_item.h index f817b458a..74ed29f68 100644 --- a/Telegram/SourceFiles/inline_bots/inline_bot_layout_item.h +++ b/Telegram/SourceFiles/inline_bots/inline_bot_layout_item.h @@ -66,8 +66,8 @@ public: virtual void paint(Painter &p, const QRect &clip, const PaintContext *context) const = 0; - virtual void setPosition(int32 position); - int32 position() const; + virtual void setPosition(int32_t position); + int32_t position() const; virtual bool isFullLine() const { return true; diff --git a/Telegram/SourceFiles/inline_bots/inline_bot_result.cpp b/Telegram/SourceFiles/inline_bots/inline_bot_result.cpp index 1741e95d8..f9d68c5b7 100644 --- a/Telegram/SourceFiles/inline_bots/inline_bot_result.cpp +++ b/Telegram/SourceFiles/inline_bots/inline_bot_result.cpp @@ -31,7 +31,7 @@ namespace InlineBots { Result::Result(const Creator &creator) : _queryId(creator.queryId), _type(creator.type) { } -std::unique_ptr Result::create(uint64 queryId, const MTPBotInlineResult &mtpData) { +std::unique_ptr Result::create(uint64_t queryId, const MTPBotInlineResult &mtpData) { using StringToTypeMap = QMap; static StaticNeverFreedPointer stringToTypeMap{ ([]() -> StringToTypeMap* { auto result = std::make_unique(); @@ -194,8 +194,8 @@ std::unique_ptr Result::create(uint64 queryId, const MTPBotInlineResult } LocationCoords location; if (result->getLocationCoords(&location)) { - int32 w = st::inlineThumbSize, h = st::inlineThumbSize; - int32 zoom = 13, scale = 1; + int32_t w = st::inlineThumbSize, h = st::inlineThumbSize; + int32_t zoom = 13, scale = 1; if (cScale() == dbisTwo || cRetina()) { scale = 2; w /= 2; diff --git a/Telegram/SourceFiles/inline_bots/inline_bot_result.h b/Telegram/SourceFiles/inline_bots/inline_bot_result.h index 0076c9c0b..86c5f0a91 100644 --- a/Telegram/SourceFiles/inline_bots/inline_bot_result.h +++ b/Telegram/SourceFiles/inline_bots/inline_bot_result.h @@ -45,11 +45,11 @@ public: // Constructor is public only for std::make_unique<>() to work. // You should use create() static method instead. explicit Result(const Creator &creator); - static std::unique_ptr create(uint64 queryId, const MTPBotInlineResult &mtpData); + static std::unique_ptr create(uint64_t queryId, const MTPBotInlineResult &mtpData); Result(const Result &other) = delete; Result &operator=(const Result &other) = delete; - uint64 getQueryId() const { + uint64_t getQueryId() const { return _queryId; } QString getId() const { @@ -99,11 +99,11 @@ private: friend class internal::SendData; friend class Layout::ItemBase; struct Creator { - uint64 queryId; + uint64_t queryId; Type type; }; - uint64 _queryId = 0; + uint64_t _queryId = 0; QString _id; Type _type = Type::Unknown; QString _title, _description, _url, _thumb_url; diff --git a/Telegram/SourceFiles/inline_bots/inline_results_widget.cpp b/Telegram/SourceFiles/inline_bots/inline_results_widget.cpp index a9548b8f0..f841f0489 100644 --- a/Telegram/SourceFiles/inline_bots/inline_results_widget.cpp +++ b/Telegram/SourceFiles/inline_bots/inline_results_widget.cpp @@ -290,7 +290,7 @@ void Inner::hideFinish(bool completely) { } } -bool Inner::inlineRowsAddItem(Result *result, Row &row, int32 &sumWidth) { +bool Inner::inlineRowsAddItem(Result *result, Row &row, int32_t &sumWidth) { auto layout = layoutPrepareInlineResult(result, (_rows.size() * MatrixRowShift) + row.items.size()); if (!layout) return false; @@ -308,7 +308,7 @@ bool Inner::inlineRowsAddItem(Result *result, Row &row, int32 &sumWidth) { return true; } -bool Inner::inlineRowFinalize(Row &row, int32 &sumWidth, bool force) { +bool Inner::inlineRowFinalize(Row &row, int32_t &sumWidth, bool force) { if (row.items.isEmpty()) return false; auto full = (row.items.size() >= kInlineItemsMaxPerRow); @@ -341,7 +341,7 @@ void Inner::clearInlineRows(bool resultsDeleted) { _rows.clear(); } -ItemBase *Inner::layoutPrepareInlineResult(Result *result, int32 position) { +ItemBase *Inner::layoutPrepareInlineResult(Result *result, int32_t position) { auto it = _inlineLayouts.find(result); if (it == _inlineLayouts.cend()) { if (auto layout = ItemBase::createLayout(this, result, _inlineWithThumb)) { @@ -373,7 +373,7 @@ void Inner::deleteUnusedInlineLayouts() { } } -Inner::Row &Inner::layoutInlineRow(Row &row, int32 sumWidth) { +Inner::Row &Inner::layoutInlineRow(Row &row, int32_t sumWidth) { auto count = int(row.items.size()); Assert(count <= kInlineItemsMaxPerRow); @@ -582,7 +582,7 @@ void Inner::inlineItemRepaint(const ItemBase *layout) { } bool Inner::inlineItemVisible(const ItemBase *layout) { - int32 position = layout->position(); + int32_t position = layout->position(); if (position < 0 || !isVisible()) { return false; } @@ -592,7 +592,7 @@ bool Inner::inlineItemVisible(const ItemBase *layout) { auto &inlineItems = _rows[row].items; int top = st::stickerPanPadding; - for (int32 i = 0; i < row; ++i) { + for (int32_t i = 0; i < row; ++i) { top += _rows.at(i).height; } diff --git a/Telegram/SourceFiles/inline_bots/inline_results_widget.h b/Telegram/SourceFiles/inline_bots/inline_results_widget.h index 6316c8836..8871b2df1 100644 --- a/Telegram/SourceFiles/inline_bots/inline_results_widget.h +++ b/Telegram/SourceFiles/inline_bots/inline_results_widget.h @@ -142,12 +142,12 @@ private: void clearInlineRows(bool resultsDeleted); std::map> _inlineLayouts; - ItemBase *layoutPrepareInlineResult(Result *result, int32 position); + ItemBase *layoutPrepareInlineResult(Result *result, int32_t position); - bool inlineRowsAddItem(Result *result, Row &row, int32 &sumWidth); - bool inlineRowFinalize(Row &row, int32 &sumWidth, bool force = false); + bool inlineRowsAddItem(Result *result, Row &row, int32_t &sumWidth); + bool inlineRowFinalize(Row &row, int32_t &sumWidth, bool force = false); - Row &layoutInlineRow(Row &row, int32 sumWidth = 0); + Row &layoutInlineRow(Row &row, int32_t sumWidth = 0); void deleteUnusedInlineLayouts(); int validateExistingInlineRows(const Results &results); diff --git a/Telegram/SourceFiles/intro/introwidget.cpp b/Telegram/SourceFiles/intro/introwidget.cpp index 7f10f232e..253af7fb2 100644 --- a/Telegram/SourceFiles/intro/introwidget.cpp +++ b/Telegram/SourceFiles/intro/introwidget.cpp @@ -39,7 +39,6 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "ui/widgets/labels.h" #include "ui/effects/widget_fade_wrap.h" #include "ui/effects/slide_animation.h" -#include "autoupdater.h" #include "window/window_slide_animation.h" #include "styles/style_boxes.h" #include "styles/style_intro.h" @@ -88,14 +87,6 @@ Widget::Widget(QWidget *parent) : TWidget(parent) getStep()->showFast(); cSetPasswordRecovered(false); - -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - Sandbox::connect(SIGNAL(updateLatest()), this, SLOT(onCheckUpdateStatus())); - Sandbox::connect(SIGNAL(updateFailed()), this, SLOT(onCheckUpdateStatus())); - Sandbox::connect(SIGNAL(updateReady()), this, SLOT(onCheckUpdateStatus())); - Sandbox::startUpdateCheck(); - onCheckUpdateStatus(); -#endif // !TDESKTOP_DISABLE_AUTOUPDATE } void Widget::refreshLang() { @@ -134,24 +125,6 @@ void Widget::createLanguageLink() { } } -#ifndef TDESKTOP_DISABLE_AUTOUPDATE -void Widget::onCheckUpdateStatus() { - if (Sandbox::updatingState() == Application::UpdatingReady) { - if (_update) return; - _update.create(this, object_ptr(this, langFactory(lng_menu_update), st::defaultBoxButton), st::introCoverDuration); - if (!_a_show.animating()) _update->show(); - _update->entity()->setClickedCallback([] { - checkReadyUpdate(); - App::restart(); - }); - } else { - if (!_update) return; - _update.destroy(); - } - updateControlsGeometry(); -} -#endif // TDESKTOP_DISABLE_AUTOUPDATE - void Widget::setInnerFocus() { if (getStep()->animating()) { setFocus(); @@ -597,7 +570,7 @@ void Widget::Step::hideDescription() { _description->hideAnimated(); } -void Widget::Step::paintContentSnapshot(Painter &p, const QPixmap &snapshot, float64 alpha, float64 howMuchHidden) { +void Widget::Step::paintContentSnapshot(Painter &p, const QPixmap &snapshot, double alpha, double howMuchHidden) { if (!snapshot.isNull()) { auto contentTop = anim::interpolate(height() - (snapshot.height() / cIntRetinaFactor()), height(), howMuchHidden); if (contentTop < height()) { @@ -613,11 +586,11 @@ void Widget::Step::prepareCoverMask() { auto maskWidth = cIntRetinaFactor(); auto maskHeight = st::introCoverHeight * cIntRetinaFactor(); auto mask = QImage(maskWidth, maskHeight, QImage::Format_ARGB32_Premultiplied); - auto maskInts = reinterpret_cast(mask.bits()); - Assert(mask.depth() == (sizeof(uint32) << 3)); + auto maskInts = reinterpret_cast(mask.bits()); + Assert(mask.depth() == (sizeof(uint32_t) << 3)); auto maskIntsPerLineAdded = (mask.bytesPerLine() >> 2) - maskWidth; Assert(maskIntsPerLineAdded >= 0); - auto realHeight = static_cast(maskHeight - 1); + auto realHeight = static_cast(maskHeight - 1); for (auto y = 0; y != maskHeight; ++y) { auto color = anim::color(st::introCoverTopBg, st::introCoverBottomBg, y / realHeight); auto colorInt = anim::getPremultiplied(color); @@ -645,7 +618,7 @@ void Widget::Step::paintCover(Painter &p, int top) { right = -outside - left; } if (top < 0) { - auto shown = float64(coverHeight) / st::introCoverHeight; + auto shown = double(coverHeight) / st::introCoverHeight; auto leftShown = qRound(shown * (left + st::introCoverLeft.width())); left = leftShown - st::introCoverLeft.width(); auto rightShown = qRound(shown * (right + st::introCoverRight.width())); @@ -657,7 +630,7 @@ void Widget::Step::paintCover(Painter &p, int top) { auto planeLeft = (width() - st::introCoverIcon.width()) / 2 - st::introCoverIconLeft; auto planeTop = top + st::introCoverIconTop; if (top < 0 && !_hasCover) { - auto deltaLeft = -qRound(float64(st::introPlaneWidth / st::introPlaneHeight) * top); + auto deltaLeft = -qRound(double(st::introPlaneWidth / st::introPlaneHeight) * top); // auto deltaTop = top; planeLeft += deltaLeft; // planeTop += top; @@ -672,7 +645,7 @@ int Widget::Step::contentLeft() const { int Widget::Step::contentTop() const { auto result = height() - st::introStepHeight - st::introStepHeightAdd; if (_hasCover) { - auto added = 1. - snap(float64(height() - st::windowMinHeight) / (st::introStepHeightFull - st::windowMinHeight), 0., 1.); + auto added = 1. - snap(double(height() - st::windowMinHeight) / (st::introStepHeightFull - st::windowMinHeight), 0., 1.); result += qRound(added * st::introStepHeightAdd); } return result; diff --git a/Telegram/SourceFiles/intro/introwidget.h b/Telegram/SourceFiles/intro/introwidget.h index 91886e64c..b344f0ea1 100644 --- a/Telegram/SourceFiles/intro/introwidget.h +++ b/Telegram/SourceFiles/intro/introwidget.h @@ -55,11 +55,6 @@ protected: signals: void countryChanged(); -#ifndef TDESKTOP_DISABLE_AUTOUPDATE -private slots: - void onCheckUpdateStatus(); -#endif // TDESKTOP_DISABLE_AUTOUPDATE - // Internal interface. public: struct Data { @@ -177,7 +172,7 @@ public: QPixmap contentSnapshotNow; }; void updateLabelsPosition(); - void paintContentSnapshot(Painter &p, const QPixmap &snapshot, float64 alpha, float64 howMuchHidden); + void paintContentSnapshot(Painter &p, const QPixmap &snapshot, double alpha, double howMuchHidden); void refreshError(); void refreshTitle(); void refreshDescription(); diff --git a/Telegram/SourceFiles/lang/lang_instance.cpp b/Telegram/SourceFiles/lang/lang_instance.cpp index 08a7f75f7..7df9be8b8 100644 --- a/Telegram/SourceFiles/lang/lang_instance.cpp +++ b/Telegram/SourceFiles/lang/lang_instance.cpp @@ -243,10 +243,10 @@ QString Instance::cloudLangCode() const { QByteArray Instance::serialize() const { auto size = Serialize::stringSize(_id); - size += sizeof(qint32); // version + size += sizeof(int32_t); // version size += Serialize::stringSize(_customFilePathAbsolute) + Serialize::stringSize(_customFilePathRelative); size += Serialize::bytearraySize(_customFileContent); - size += sizeof(qint32); // _nonDefaultValues.size() + size += sizeof(int32_t); // _nonDefaultValues.size() for (auto &nonDefault : _nonDefaultValues) { size += Serialize::bytearraySize(nonDefault.first) + Serialize::bytearraySize(nonDefault.second); } @@ -256,9 +256,9 @@ QByteArray Instance::serialize() const { { QDataStream stream(&result, QIODevice::WriteOnly); stream.setVersion(QDataStream::Qt_5_1); - stream << _id << qint32(_version); + stream << _id << int32_t(_version); stream << _customFilePathAbsolute << _customFilePathRelative << _customFileContent; - stream << qint32(_nonDefaultValues.size()); + stream << int32_t(_nonDefaultValues.size()); for (auto &nonDefault : _nonDefaultValues) { stream << nonDefault.first << nonDefault.second; } @@ -270,10 +270,10 @@ void Instance::fillFromSerialized(const QByteArray &data) { QDataStream stream(data); stream.setVersion(QDataStream::Qt_5_1); QString id; - qint32 version = 0; + int32_t version = 0; QString customFilePathAbsolute, customFilePathRelative; QByteArray customFileContent; - qint32 nonDefaultValuesCount = 0; + int32_t nonDefaultValuesCount = 0; stream >> id >> version; stream >> customFilePathAbsolute >> customFilePathRelative >> customFileContent; stream >> nonDefaultValuesCount; diff --git a/Telegram/SourceFiles/lang/lang_tag.cpp b/Telegram/SourceFiles/lang/lang_tag.cpp index 32bb224d9..42466abf0 100644 --- a/Telegram/SourceFiles/lang/lang_tag.cpp +++ b/Telegram/SourceFiles/lang/lang_tag.cpp @@ -154,7 +154,7 @@ int FindTagReplacementPosition(const QString &original, ushort tag) { } -PluralResult Plural(ushort keyBase, float64 value) { +PluralResult Plural(ushort keyBase, double value) { // Simplified. auto n = qAbs(value); auto i = qFloor(n); diff --git a/Telegram/SourceFiles/lang/lang_tag.h b/Telegram/SourceFiles/lang/lang_tag.h index 6f11b0f30..2d1da2290 100644 --- a/Telegram/SourceFiles/lang/lang_tag.h +++ b/Telegram/SourceFiles/lang/lang_tag.h @@ -30,7 +30,7 @@ struct PluralResult { QString string; QString replacement; }; -PluralResult Plural(ushort keyBase, float64 value); +PluralResult Plural(ushort keyBase, double value); void UpdatePluralRules(const QString &languageId); template diff --git a/Telegram/SourceFiles/layout.cpp b/Telegram/SourceFiles/layout.cpp index 89e67b03c..9b3ce368c 100644 --- a/Telegram/SourceFiles/layout.cpp +++ b/Telegram/SourceFiles/layout.cpp @@ -90,27 +90,27 @@ const TextParseOptions &itemTextNoMonoOptions(const HistoryItem *item) { return itemTextNoMonoOptions(item->history(), item->author()); } -QString formatSizeText(qint64 size) { +QString formatSizeText(int64_t size) { if (size >= 1024 * 1024) { // more than 1 mb - qint64 sizeTenthMb = (size * 10 / (1024 * 1024)); + int64_t sizeTenthMb = (size * 10 / (1024 * 1024)); return QString::number(sizeTenthMb / 10) + '.' + QString::number(sizeTenthMb % 10) + qsl(" MB"); } if (size >= 1024) { - qint64 sizeTenthKb = (size * 10 / 1024); + int64_t sizeTenthKb = (size * 10 / 1024); return QString::number(sizeTenthKb / 10) + '.' + QString::number(sizeTenthKb % 10) + qsl(" KB"); } return QString::number(size) + qsl(" B"); } -QString formatDownloadText(qint64 ready, qint64 total) { +QString formatDownloadText(int64_t ready, int64_t total) { QString readyStr, totalStr, mb; if (total >= 1024 * 1024) { // more than 1 mb - qint64 readyTenthMb = (ready * 10 / (1024 * 1024)), totalTenthMb = (total * 10 / (1024 * 1024)); + int64_t readyTenthMb = (ready * 10 / (1024 * 1024)), totalTenthMb = (total * 10 / (1024 * 1024)); readyStr = QString::number(readyTenthMb / 10) + '.' + QString::number(readyTenthMb % 10); totalStr = QString::number(totalTenthMb / 10) + '.' + QString::number(totalTenthMb % 10); mb = qsl("MB"); } else if (total >= 1024) { - qint64 readyKb = (ready / 1024), totalKb = (total / 1024); + int64_t readyKb = (ready / 1024), totalKb = (total / 1024); readyStr = QString::number(readyKb); totalStr = QString::number(totalKb); mb = qsl("KB"); @@ -122,12 +122,12 @@ QString formatDownloadText(qint64 ready, qint64 total) { return lng_save_downloaded(lt_ready, readyStr, lt_total, totalStr, lt_mb, mb); } -QString formatDurationText(qint64 duration) { - qint64 hours = (duration / 3600), minutes = (duration % 3600) / 60, seconds = duration % 60; +QString formatDurationText(int64_t duration) { + int64_t hours = (duration / 3600), minutes = (duration % 3600) / 60, seconds = duration % 60; return (hours ? QString::number(hours) + ':' : QString()) + (minutes >= 10 ? QString() : QString('0')) + QString::number(minutes) + ':' + (seconds >= 10 ? QString() : QString('0')) + QString::number(seconds); } -QString formatDurationWords(qint64 duration) { +QString formatDurationWords(int64_t duration) { if (duration > 59) { auto minutes = (duration / 60); auto minutesCount = lng_duration_minsec_minutes(lt_count, minutes); @@ -138,24 +138,24 @@ QString formatDurationWords(qint64 duration) { return lng_duration_seconds(lt_count, duration); } -QString formatDurationAndSizeText(qint64 duration, qint64 size) { +QString formatDurationAndSizeText(int64_t duration, int64_t size) { return lng_duration_and_size(lt_duration, formatDurationText(duration), lt_size, formatSizeText(size)); } -QString formatGifAndSizeText(qint64 size) { +QString formatGifAndSizeText(int64_t size) { return lng_duration_and_size(lt_duration, qsl("GIF"), lt_size, formatSizeText(size)); } -QString formatPlayedText(qint64 played, qint64 duration) { +QString formatPlayedText(int64_t played, int64_t duration) { return lng_duration_played(lt_played, formatDurationText(played), lt_duration, formatDurationText(duration)); } -int32 documentColorIndex(DocumentData *document, QString &ext) { - int32 colorIndex = 0; +int32_t documentColorIndex(DocumentData *document, QString &ext) { + int32_t colorIndex = 0; QString name = document ? (document->name.isEmpty() ? (document->sticker() ? lang(lng_in_dlg_sticker) : qsl("Unknown File")) : document->name) : lang(lng_message_empty); name = name.toLower(); - int32 lastDot = name.lastIndexOf('.'); + int32_t lastDot = name.lastIndexOf('.'); QString mime = document ? document->mime.toLower() : QString(); if (name.endsWith(qstr(".doc")) || name.endsWith(qstr(".txt")) || @@ -193,7 +193,7 @@ int32 documentColorIndex(DocumentData *document, QString &ext) { return colorIndex; } -style::color documentColor(int32 colorIndex) { +style::color documentColor(int32_t colorIndex) { const style::color colors[] = { st::msgFile1Bg, st::msgFile2Bg, @@ -203,7 +203,7 @@ style::color documentColor(int32 colorIndex) { return colors[colorIndex & 3]; } -style::color documentDarkColor(int32 colorIndex) { +style::color documentDarkColor(int32_t colorIndex) { static style::color colors[] = { st::msgFile1BgDark, st::msgFile2BgDark, @@ -213,7 +213,7 @@ style::color documentDarkColor(int32 colorIndex) { return colors[colorIndex & 3]; } -style::color documentOverColor(int32 colorIndex) { +style::color documentOverColor(int32_t colorIndex) { static style::color colors[] = { st::msgFile1BgOver, st::msgFile2BgOver, @@ -223,7 +223,7 @@ style::color documentOverColor(int32 colorIndex) { return colors[colorIndex & 3]; } -style::color documentSelectedColor(int32 colorIndex) { +style::color documentSelectedColor(int32_t colorIndex) { static style::color colors[] = { st::msgFile1BgSelected, st::msgFile2BgSelected, @@ -233,7 +233,7 @@ style::color documentSelectedColor(int32 colorIndex) { return colors[colorIndex & 3]; } -RoundCorners documentCorners(int32 colorIndex) { +RoundCorners documentCorners(int32_t colorIndex) { return RoundCorners(Doc1Corners + (colorIndex & 3)); } diff --git a/Telegram/SourceFiles/layout.h b/Telegram/SourceFiles/layout.h index 333db4394..b9400dafb 100644 --- a/Telegram/SourceFiles/layout.h +++ b/Telegram/SourceFiles/layout.h @@ -68,19 +68,19 @@ enum RoundCorners { RoundCornersCount }; -static const int32 FileStatusSizeReady = 0x7FFFFFF0; -static const int32 FileStatusSizeLoaded = 0x7FFFFFF1; -static const int32 FileStatusSizeFailed = 0x7FFFFFF2; +static const int32_t FileStatusSizeReady = 0x7FFFFFF0; +static const int32_t FileStatusSizeLoaded = 0x7FFFFFF1; +static const int32_t FileStatusSizeFailed = 0x7FFFFFF2; -QString formatSizeText(qint64 size); -QString formatDownloadText(qint64 ready, qint64 total); -QString formatDurationText(qint64 duration); -QString formatDurationWords(qint64 duration); -QString formatDurationAndSizeText(qint64 duration, qint64 size); -QString formatGifAndSizeText(qint64 size); -QString formatPlayedText(qint64 played, qint64 duration); +QString formatSizeText(int64_t size); +QString formatDownloadText(int64_t ready, int64_t total); +QString formatDurationText(int64_t duration); +QString formatDurationWords(int64_t duration); +QString formatDurationAndSizeText(int64_t duration, int64_t size); +QString formatGifAndSizeText(int64_t size); +QString formatPlayedText(int64_t played, int64_t duration); -int32 documentColorIndex(DocumentData *document, QString &ext); +int32_t documentColorIndex(DocumentData *document, QString &ext); style::color documentColor(int colorIndex); style::color documentDarkColor(int colorIndex); style::color documentOverColor(int colorIndex); @@ -123,7 +123,7 @@ public: link.clear(); cursor = HistoryDefaultCursorState; } - virtual void getSymbol(uint16 &symbol, bool &after, bool &upon, QPoint point) const { // from text + virtual void getSymbol(uint16_t &symbol, bool &after, bool &upon, QPoint point) const { // from text upon = hasPoint(point); symbol = upon ? 0xFFFF : 0; after = false; diff --git a/Telegram/SourceFiles/logs.cpp b/Telegram/SourceFiles/logs.cpp index d916756c8..25c0698e9 100644 --- a/Telegram/SourceFiles/logs.cpp +++ b/Telegram/SourceFiles/logs.cpp @@ -40,9 +40,9 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include #ifdef MAC_USE_BREAKPAD -#include "client/mac/handler/exception_handler.h" +//#include "client/mac/handler/exception_handler.h" #else // MAC_USE_BREAKPAD -#include "client/crashpad_client.h" +//#include "client/crashpad_client.h" #endif // else for MAC_USE_BREAKPAD #elif defined Q_OS_LINUX64 || defined Q_OS_LINUX32 // Q_OS_MAC @@ -82,9 +82,9 @@ QString _logsFilePath(LogDataType type, const QString &postfix = QString()) { return path; } -int32 LogsStartIndexChosen = -1; +int32_t LogsStartIndexChosen = -1; QString _logsEntryStart() { - static int32 index = 0; + static int32_t index = 0; QDateTime tm(QDateTime::currentDateTime()); auto thread = qobject_cast(QThread::currentThread()); @@ -97,7 +97,7 @@ class LogsDataFields { public: LogsDataFields() { - for (int32 i = 0; i < LogDataCount; ++i) { + for (int32_t i = 0; i < LogDataCount; ++i) { files[i].reset(new QFile()); } } @@ -144,9 +144,9 @@ private: QSharedPointer files[LogDataCount]; QTextStream streams[LogDataCount]; - int32 part = -1; + int32_t part = -1; - bool reopen(LogDataType type, int32 dayIndex, const QString &postfix) { + bool reopen(LogDataType type, int32_t dayIndex, const QString &postfix) { if (streams[type].device()) { if (type == LogDataMain) { if (!postfix.isEmpty()) { @@ -197,9 +197,9 @@ private: return false; } else { bool found = false; - int32 oldest = -1; // find not existing log_startX.txt or pick the oldest one (by lastModified) + int32_t oldest = -1; // find not existing log_startX.txt or pick the oldest one (by lastModified) QDateTime oldestLastModified; - for (int32 i = 0; i < 10; ++i) { + for (int32_t i = 0; i < 10; ++i) { QString trying = _logsFilePath(type, qsl("_start%1").arg(i)); files[type]->setFileName(trying); if (!files[type]->exists()) { @@ -253,12 +253,12 @@ private: mylocaltime(&tm, &t); static const int switchEach = 15; // minutes - int32 newPart = (tm.tm_min + tm.tm_hour * 60) / switchEach; + int32_t newPart = (tm.tm_min + tm.tm_hour * 60) / switchEach; if (newPart == part) return; part = newPart; - int32 dayIndex = (tm.tm_year + 1900) * 10000 + (tm.tm_mon + 1) * 100 + tm.tm_mday; + int32_t dayIndex = (tm.tm_year + 1900) * 10000 + (tm.tm_mon + 1) * 100 + tm.tm_mday; QString postfix = QString("_%4_%5").arg((part * switchEach) / 60, 2, 10, QChar('0')).arg((part * switchEach) % 60, 2, 10, QChar('0')); reopen(LogDataDebug, dayIndex, postfix); @@ -480,7 +480,7 @@ namespace Logs { _logsWrite(LogDataDebug, debugmsg); } - void writeDebug(const char *file, int32 line, const QString &v) { + void writeDebug(const char *file, int32_t line, const QString &v) { const char *last = strstr(file, "/"), *found = 0; while (last) { found = last; @@ -512,7 +512,7 @@ namespace Logs { _logsWrite(LogDataTcp, msg); } - void writeMtp(int32 dc, const QString &v) { + void writeMtp(int32_t dc, const QString &v) { QString msg(QString("%1 (dc:%2) %3\n").arg(_logsEntryStart()).arg(dc).arg(v)); _logsWrite(LogDataMtp, msg); } @@ -525,7 +525,7 @@ namespace Logs { return LogsBeforeSingleInstanceChecked; } - int32 size = LogsBeforeSingleInstanceChecked.size(); + int32_t size = LogsBeforeSingleInstanceChecked.size(); for (LogsInMemoryList::const_iterator i = LogsInMemory->cbegin(), e = LogsInMemory->cend(); i != e; ++i) { if (i->first == LogDataMain) { size += i->second.size(); @@ -553,10 +553,10 @@ namespace Logs { return idsStr + "]"; } - QString vector(const QVector &ids) { + QString vector(const QVector &ids) { if (!ids.size()) return "[]"; QString idsStr = QString("[%1").arg(*ids.cbegin()); - for (QVector::const_iterator i = ids.cbegin() + 1, e = ids.cend(); i != e; ++i) { + for (QVector::const_iterator i = ids.cbegin() + 1, e = ids.cend(); i != e; ++i) { idsStr += QString(", %2").arg(*i); } return idsStr + "]"; @@ -727,7 +727,7 @@ namespace internal { internal::writeChar('-'); num = -num; } - internal::writeNumber(stream, uint64(floor(num))); + internal::writeNumber(stream, uint64_t(floor(num))); internal::writeChar('.'); num -= floor(num); for (int i = 0; i < 4; ++i) { @@ -820,16 +820,16 @@ namespace internal { dump() << "\n"; } if (name) { - dump() << "Caught signal " << signum << " (" << name << ") in thread " << uint64(thread) << "\n"; + dump() << "Caught signal " << signum << " (" << name << ") in thread " << uint64_t(thread) << "\n"; } else if (signum == -1) { - dump() << "Google Breakpad caught a crash, minidump written in thread " << uint64(thread) << "\n"; + dump() << "Google Breakpad caught a crash, minidump written in thread " << uint64_t(thread) << "\n"; if (BreakpadDumpPath) { dump() << "Minidump: " << BreakpadDumpPath << "\n"; } else if (BreakpadDumpPathW) { dump() << "Minidump: " << BreakpadDumpPathW << "\n"; } } else { - dump() << "Caught signal " << signum << " in thread " << uint64(thread) << "\n"; + dump() << "Caught signal " << signum << " in thread " << uint64_t(thread) << "\n"; } // see https://github.com/benbjohnson/bandicoot @@ -886,7 +886,7 @@ namespace internal { Dl_info info; dump() << i << " "; if (dladdr(addresses[i], &info)) { - dump() << uint64(info.dli_fbase) << " (" << info.dli_fname << ")\n"; + dump() << uint64_t(info.dli_fbase) << " (" << info.dli_fname << ")\n"; } else { dump() << "_unknown_module_\n"; } @@ -985,17 +985,17 @@ namespace internal { #endif // !_DEBUG internal::SetSignalHandlers = false; #else // MAC_USE_BREAKPAD - crashpad::CrashpadClient crashpad_client; + //crashpad::CrashpadClient crashpad_client; std::string handler = (cExeDir() + cExeName() + qsl("/Contents/Helpers/crashpad_handler")).toUtf8().constData(); std::string database = QFile::encodeName(dumpspath).constData(); - if (crashpad_client.StartHandler(base::FilePath(handler), + /*if (crashpad_client.StartHandler(base::FilePath(handler), base::FilePath(database), std::string(), ProcessAnnotations, std::vector(), false)) { crashpad_client.UseHandler(); - } + }*/ #endif // else for MAC_USE_BREAKPAD #elif defined Q_OS_LINUX64 || defined Q_OS_LINUX32 internal::BreakpadExceptionHandler = new google_breakpad::ExceptionHandler( @@ -1037,7 +1037,7 @@ namespace internal { #endif // else for !Q_OS_WIN QByteArray lastdump; char buffer[256 * 1024] = { 0 }; - int32 read = fread(buffer, 1, 256 * 1024, f); + int32_t read = fread(buffer, 1, 256 * 1024, f); if (read > 0) { lastdump.append(buffer, read); } @@ -1139,5 +1139,19 @@ namespace internal { internal::ProcessAnnotationRefs.erase(key); } } - } + +#ifdef TDESKTOP_DISABLE_CRASH_REPORTS + +namespace SignalHandlers { + dump::~dump() { + } + const dump &operator<<(const dump &stream, const char *str) { + return stream; + } + const dump &operator<<(const dump &stream, double num) { + return stream; + } +} + +#endif // TDESKTOP_DISABLE_CRASH_REPORTS diff --git a/Telegram/SourceFiles/logs.h b/Telegram/SourceFiles/logs.h index 3e70555b3..bb834eea0 100644 --- a/Telegram/SourceFiles/logs.h +++ b/Telegram/SourceFiles/logs.h @@ -34,9 +34,9 @@ namespace Logs { void writeMain(const QString &v); - void writeDebug(const char *file, int32 line, const QString &v); + void writeDebug(const char *file, int32_t line, const QString &v); void writeTcp(const QString &v); - void writeMtp(int32 dc, const QString &v); + void writeMtp(int32_t dc, const QString &v); QString full(); @@ -45,14 +45,14 @@ namespace Logs { } struct MemoryBuffer { - MemoryBuffer(const void *ptr, uint32 size) : p(ptr), s(size) { + MemoryBuffer(const void *ptr, uint32_t size) : p(ptr), s(size) { } QString str() const { QString result; const uchar *buf((const uchar*)p); const char *hex = "0123456789ABCDEF"; result.reserve(s * 3); - for (uint32 i = 0; i < s; ++i) { + for (uint32_t i = 0; i < s; ++i) { result += hex[(buf[i] >> 4)]; result += hex[buf[i] & 0x0F]; result += ' '; @@ -62,15 +62,15 @@ namespace Logs { } const void *p; - uint32 s; + uint32_t s; }; - inline MemoryBuffer mb(const void *ptr, uint32 size) { + inline MemoryBuffer mb(const void *ptr, uint32_t size) { return MemoryBuffer(ptr, size); } QString vector(const QVector &ids); - QString vector(const QVector &ids); + QString vector(const QVector &ids); } diff --git a/Telegram/SourceFiles/main.cpp b/Telegram/SourceFiles/main.cpp index 6e85f27dc..a43dc91f5 100644 --- a/Telegram/SourceFiles/main.cpp +++ b/Telegram/SourceFiles/main.cpp @@ -23,9 +23,10 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "storage/localstorage.h" int main(int argc, char *argv[]) { -#ifndef Q_OS_MAC // Retina display support is working fine, others are not. +#if !defined(Q_OS_MAC) && QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) + // Retina display support is working fine, others are not. QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true); -#endif // Q_OS_MAC +#endif // not defined Q_OS_MAC and QT_VERSION >= 5.6.0 QCoreApplication::setApplicationName(qsl("TelegramDesktop")); InitFromCommandLine(argc, argv); @@ -38,6 +39,13 @@ int main(int argc, char *argv[]) { // both are finished in Application::closeApplication Logs::start(); // must be started before Platform is started Platform::start(); // must be started before QApplication is created +#if defined(Q_OS_LINUX64) + QCoreApplication::addLibraryPath("/usr/lib64/qt5/plugins"); +#else + QCoreApplication::addLibraryPath("/usr/lib/qt5/plugins"); +#endif + qputenv("QT_STYLE_OVERRIDE", "qwerty"); + qunsetenv("QT_QPA_PLATFORMTHEME"); int result = 0; { @@ -47,12 +55,6 @@ int main(int argc, char *argv[]) { DEBUG_LOG(("Telegram finished, result: %1").arg(result)); -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - if (cRestartingUpdate()) { - DEBUG_LOG(("Application Info: executing updater to install update...")); - psExecUpdater(); - } else -#endif // !TDESKTOP_DISABLE_AUTOUPDATE if (cRestarting()) { DEBUG_LOG(("Application Info: executing Telegram, because of restart...")); psExecTelegram(); diff --git a/Telegram/SourceFiles/mainwidget.cpp b/Telegram/SourceFiles/mainwidget.cpp index bcb621c6d..e40944115 100644 --- a/Telegram/SourceFiles/mainwidget.cpp +++ b/Telegram/SourceFiles/mainwidget.cpp @@ -155,7 +155,7 @@ MainWidget::MainWidget(QWidget *parent, not_null controller subscribe(_controller->dialogsListDisplayForced(), [this](bool) { updateDialogsWidthAnimated(); }); - subscribe(_controller->dialogsWidthRatio(), [this](float64) { + subscribe(_controller->dialogsWidthRatio(), [this](double) { updateControlsGeometry(); }); subscribe(_controller->floatPlayerAreaUpdated(), [this] { @@ -233,10 +233,6 @@ MainWidget::MainWidget(QWidget *parent, not_null controller orderWidgets(); _sideResizeArea->installEventFilter(this); - -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - Sandbox::startUpdateCheck(); -#endif // !TDESKTOP_DISABLE_AUTOUPDATE } void MainWidget::checkCurrentFloatPlayer() { @@ -626,7 +622,7 @@ void MainWidget::finishForwarding(History *history, bool silent) { ids.reserve(toForward.size()); randomIds.reserve(toForward.size()); for (auto i = toForward.cbegin(), e = toForward.cend(); i != e; ++i) { - auto randomId = rand_value(); + auto randomId = rand_value(); if (genClientSideMessage) { if (auto message = i.value()->toHistoryMessage()) { auto newId = FullMsgId(peerToChannel(history->peer->id), clientMsgId()); @@ -699,9 +695,9 @@ void MainWidget::webPagesOrGamesUpdate() { } } -void MainWidget::updateMutedIn(int32 seconds) { +void MainWidget::updateMutedIn(int32_t seconds) { if (seconds > 86400) seconds = 86400; - int32 ms = seconds * 1000; + int32_t ms = seconds * 1000; if (_updateMutedTimer.isActive() && _updateMutedTimer.remainingTime() <= ms) return; _updateMutedTimer.start(ms); } @@ -1417,7 +1413,7 @@ void MainWidget::sendMessage(const MessageToSend &message) { auto replyTo = (message.replyTo < 0) ? _history->replyToId() : message.replyTo; while (TextUtilities::CutPart(sending, left, MaxMessageSize)) { auto newId = FullMsgId(peerToChannel(history->peer->id), clientMsgId()); - auto randomId = rand_value(); + auto randomId = rand_value(); TextUtilities::Trim(sending); @@ -1477,7 +1473,7 @@ void MainWidget::saveRecentHashtags(const QString &text) { bool found = false; QRegularExpressionMatch m; RecentHashtagPack recent(cRecentWriteHashtags()); - for (int32 i = 0, next = 0; (m = TextUtilities::RegExpHashtag().match(text, i)).hasMatch(); i = next) { + for (int32_t i = 0, next = 0; (m = TextUtilities::RegExpHashtag().match(text, i)).hasMatch(); i = next) { i = m.capturedStart(); next = m.capturedEnd(); if (m.hasMatch()) { @@ -1576,7 +1572,7 @@ bool MainWidget::preloadOverview(PeerData *peer, MediaOverviewType type) { void MainWidget::overviewPreloaded(PeerData *peer, const MTPmessages_Messages &result, mtpRequestId req) { MediaOverviewType type = OverviewCount; - for (int32 i = 0; i < OverviewCount; ++i) { + for (int32_t i = 0; i < OverviewCount; ++i) { OverviewsPreload::iterator j = _overviewPreload[i].find(peer); if (j != _overviewPreload[i].end() && j.value() == req) { type = MediaOverviewType(i); @@ -1609,7 +1605,7 @@ bool MainWidget::overviewFailed(PeerData *peer, const RPCError &error, mtpReques if (MTP::isDefaultHandledError(error)) return false; MediaOverviewType type = OverviewCount; - for (int32 i = 0; i < OverviewCount; ++i) { + for (int32_t i = 0; i < OverviewCount; ++i) { OverviewsPreload::iterator j = _overviewPreload[i].find(peer); if (j != _overviewPreload[i].end() && j.value() == req) { _overviewPreload[i].erase(j); @@ -1648,7 +1644,7 @@ void MainWidget::checkLastUpdate(bool afterSleep) { void MainWidget::overviewLoaded(not_null history, const MTPmessages_Messages &result, mtpRequestId req) { OverviewsPreload::iterator it; MediaOverviewType type = OverviewCount; - for (int32 i = 0; i < OverviewCount; ++i) { + for (int32_t i = 0; i < OverviewCount; ++i) { it = _overviewLoad[i].find(history->peer); if (it != _overviewLoad[i].cend()) { type = MediaOverviewType(i); @@ -1711,11 +1707,11 @@ void MainWidget::messagesAffected(PeerData *peer, const MTPmessages_AffectedMess } } -void MainWidget::ui_showPeerHistoryAsync(quint64 peerId, qint32 showAtMsgId, Ui::ShowWay way) { +void MainWidget::ui_showPeerHistoryAsync(uint64_t peerId, int32_t showAtMsgId, Ui::ShowWay way) { Ui::showPeerHistory(peerId, showAtMsgId, way); } -void MainWidget::ui_autoplayMediaInlineAsync(qint32 channelId, qint32 msgId) { +void MainWidget::ui_autoplayMediaInlineAsync(int32_t channelId, int32_t msgId) { if (HistoryItem *item = App::histItemById(channelId, msgId)) { if (HistoryMedia *media = item->getMedia()) { media->playInline(true); @@ -2032,7 +2028,7 @@ void MainWidget::dialogsCancelled() { _history->activate(); } -void MainWidget::insertCheckedServiceNotification(const TextWithEntities &message, const MTPMessageMedia &media, int32 date) { +void MainWidget::insertCheckedServiceNotification(const TextWithEntities &message, const MTPMessageMedia &media, int32_t date) { auto flags = MTPDmessage::Flag::f_entities | MTPDmessage::Flag::f_from_id | MTPDmessage_ClientFlag::f_clientside_unread; auto sending = TextWithEntities(), left = message; HistoryItem *item = nullptr; @@ -2117,7 +2113,7 @@ bool MainWidget::chatBackgroundLoading() { return (_background != nullptr); } -float64 MainWidget::chatBackgroundProgress() const { +double MainWidget::chatBackgroundProgress() const { if (_background) { return _background->full->progress(); } @@ -2366,7 +2362,7 @@ void MainWidget::viewsIncrementDone(QVector ids, const MTPVector if (i.value() == req) { PeerData *peer = i.key(); ChannelId channel = peerToChannel(peer->id); - for (int32 j = 0, l = ids.size(); j < l; ++j) { + for (int32_t j = 0, l = ids.size(); j < l; ++j) { if (HistoryItem *item = App::histItemById(channel, ids.at(j).v)) { item->setViewsCount(v.at(j).v); } @@ -2418,7 +2414,7 @@ void MainWidget::ctrlEnterSubmitUpdated() { _history->updateFieldSubmitSettings(); } -void MainWidget::ui_showPeerHistory(quint64 peerId, qint32 showAtMsgId, Ui::ShowWay way) { +void MainWidget::ui_showPeerHistory(uint64_t peerId, int32_t showAtMsgId, Ui::ShowWay way) { if (auto peer = App::peerLoaded(peerId)) { if (peer->migrateTo()) { peer = peer->migrateTo(); @@ -2629,7 +2625,7 @@ void MainWidget::saveSectionInStack() { } } -void MainWidget::showMediaOverview(PeerData *peer, MediaOverviewType type, bool back, int32 lastScrollTop) { +void MainWidget::showMediaOverview(PeerData *peer, MediaOverviewType type, bool back, int32_t lastScrollTop) { if (peer->migrateTo()) { peer = peer->migrateTo(); } @@ -3008,7 +3004,7 @@ void MainWidget::windowShown() { _history->windowShown(); } -void MainWidget::sentUpdatesReceived(uint64 randomId, const MTPUpdates &result) { +void MainWidget::sentUpdatesReceived(uint64_t randomId, const MTPUpdates &result) { feedUpdates(result, randomId); } @@ -3315,13 +3311,13 @@ bool MainWidget::eventFilter(QObject *o, QEvent *e) { } else if (e->type() == QEvent::MouseButtonRelease) { _resizingSide = false; if (!Adaptive::OneColumn()) { - _controller->dialogsWidthRatio().set(float64(_dialogsWidth) / width(), true); + _controller->dialogsWidthRatio().set(double(_dialogsWidth) / width(), true); } Local::writeUserSettings(); } else if (e->type() == QEvent::MouseMove && _resizingSide) { auto newWidth = mouseLeft() - _resizingSideShift; accumulate_max(newWidth, _controller->dialogsSmallColumnWidth()); - _controller->dialogsWidthRatio().set(float64(newWidth) / width(), true); + _controller->dialogsWidthRatio().set(double(newWidth) / width(), true); } } else if (e->type() == QEvent::FocusIn) { if (auto widget = qobject_cast(o)) { @@ -3375,7 +3371,7 @@ void MainWidget::updateWindowAdaptiveLayout() { layout.windowLayout = Adaptive::WindowLayout::Normal; layout.dialogsWidth = st::dialogsWidthMin; layout.chatWidth = layout.bodyWidth - layout.dialogsWidth; - dialogsWidthRatio = float64(layout.dialogsWidth) / layout.bodyWidth; + dialogsWidthRatio = double(layout.dialogsWidth) / layout.bodyWidth; } } @@ -3396,7 +3392,7 @@ void MainWidget::updateWindowAdaptiveLayout() { if (extendChatBy > 0) { layout.dialogsWidth -= extendChatBy; layout.chatWidth += extendChatBy; - dialogsWidthRatio = float64(layout.dialogsWidth) / layout.bodyWidth; + dialogsWidthRatio = double(layout.dialogsWidth) / layout.bodyWidth; } } } @@ -3484,7 +3480,7 @@ bool MainWidget::updateFail(const RPCError &e) { return true; } -void MainWidget::updSetState(int32 pts, int32 date, int32 qts, int32 seq) { +void MainWidget::updSetState(int32_t pts, int32_t date, int32_t qts, int32_t seq) { if (pts) { _ptsWaiter.init(pts); } @@ -3497,8 +3493,8 @@ void MainWidget::updSetState(int32 pts, int32 date, int32 qts, int32 seq) { if (seq && seq != updSeq) { updSeq = seq; if (_bySeqTimer.isActive()) _bySeqTimer.stop(); - for (QMap::iterator i = _bySeqUpdates.begin(); i != _bySeqUpdates.end();) { - int32 s = i.key(); + for (QMap::iterator i = _bySeqUpdates.begin(); i != _bySeqUpdates.end();) { + int32_t s = i.key(); if (s <= seq + 1) { MTPUpdates v = i.value(); i = _bySeqUpdates.erase(i); @@ -3516,7 +3512,7 @@ void MainWidget::updSetState(int32 pts, int32 date, int32 qts, int32 seq) { void MainWidget::gotChannelDifference(ChannelData *channel, const MTPupdates_ChannelDifference &diff) { _channelFailDifferenceTimeout.remove(channel); - int32 timeout = 0; + int32_t timeout = 0; bool isFinal = true; switch (diff.type()) { case mtpc_updates_channelDifferenceEmpty: { @@ -3569,7 +3565,7 @@ void MainWidget::gotChannelDifference(ChannelData *channel, const MTPupdates_Cha // feed messages and groups, copy from App::feedMsgs auto h = App::history(channel->id); auto &vmsgs = d.vnew_messages.v; - QMap msgsIds; + QMap msgsIds; for (int i = 0, l = vmsgs.size(); i < l; ++i) { auto &msg = vmsgs[i]; switch (msg.type()) { @@ -3578,11 +3574,11 @@ void MainWidget::gotChannelDifference(ChannelData *channel, const MTPupdates_Cha if (App::checkEntitiesAndViewsUpdate(d)) { // new message, index my forwarded messages to links _overview, already in blocks LOG(("Skipping message, because it is already in blocks!")); } else { - msgsIds.insert((uint64(uint32(d.vid.v)) << 32) | uint64(i), i + 1); + msgsIds.insert((uint64_t(uint32_t(d.vid.v)) << 32) | uint64_t(i), i + 1); } } break; - case mtpc_messageEmpty: msgsIds.insert((uint64(uint32(msg.c_messageEmpty().vid.v)) << 32) | uint64(i), i + 1); break; - case mtpc_messageService: msgsIds.insert((uint64(uint32(msg.c_messageService().vid.v)) << 32) | uint64(i), i + 1); break; + case mtpc_messageEmpty: msgsIds.insert((uint64_t(uint32_t(msg.c_messageEmpty().vid.v)) << 32) | uint64_t(i), i + 1); break; + case mtpc_messageService: msgsIds.insert((uint64_t(uint32_t(msg.c_messageService().vid.v)) << 32) | uint64_t(i), i + 1); break; } } for_const (auto msgIndex, msgsIds) { @@ -3616,7 +3612,7 @@ void MainWidget::gotChannelDifference(ChannelData *channel, const MTPupdates_Cha } void MainWidget::gotRangeDifference(ChannelData *channel, const MTPupdates_ChannelDifference &diff) { - int32 nextRequestPts = 0; + int32_t nextRequestPts = 0; bool isFinal = true; switch (diff.type()) { case mtpc_updates_channelDifferenceEmpty: { @@ -3718,7 +3714,7 @@ void MainWidget::gotDifference(const MTPupdates_Difference &difference) { }; } -bool MainWidget::getDifferenceTimeChanged(ChannelData *channel, int32 ms, ChannelGetDifferenceTime &channelCurTime, TimeMs &curTime) { +bool MainWidget::getDifferenceTimeChanged(ChannelData *channel, int32_t ms, ChannelGetDifferenceTime &channelCurTime, TimeMs &curTime) { if (channel) { if (ms <= 0) { ChannelGetDifferenceTime::iterator i = channelCurTime.find(channel); @@ -3759,14 +3755,14 @@ bool MainWidget::getDifferenceTimeChanged(ChannelData *channel, int32 ms, Channe return true; } -void MainWidget::ptsWaiterStartTimerFor(ChannelData *channel, int32 ms) { +void MainWidget::ptsWaiterStartTimerFor(ChannelData *channel, int32_t ms) { if (getDifferenceTimeChanged(channel, ms, _channelGetDifferenceTimeByPts, _getDifferenceTimeByPts)) { onGetDifferenceTimeByPts(); } } void MainWidget::failDifferenceStartTimerFor(ChannelData *channel) { - int32 ms = 0; + int32_t ms = 0; ChannelFailDifferenceTimeout::iterator i; if (channel) { i = _channelFailDifferenceTimeout.find(channel); @@ -3787,15 +3783,15 @@ void MainWidget::failDifferenceStartTimerFor(ChannelData *channel) { } } -bool MainWidget::ptsUpdateAndApply(int32 pts, int32 ptsCount, const MTPUpdates &updates) { +bool MainWidget::ptsUpdateAndApply(int32_t pts, int32_t ptsCount, const MTPUpdates &updates) { return _ptsWaiter.updateAndApply(nullptr, pts, ptsCount, updates); } -bool MainWidget::ptsUpdateAndApply(int32 pts, int32 ptsCount, const MTPUpdate &update) { +bool MainWidget::ptsUpdateAndApply(int32_t pts, int32_t ptsCount, const MTPUpdate &update) { return _ptsWaiter.updateAndApply(nullptr, pts, ptsCount, update); } -bool MainWidget::ptsUpdateAndApply(int32 pts, int32 ptsCount) { +bool MainWidget::ptsUpdateAndApply(int32_t pts, int32_t ptsCount) { return _ptsWaiter.updateAndApply(nullptr, pts, ptsCount); } @@ -3998,10 +3994,10 @@ void MainWidget::joinGroupByHash(const QString &hash) { void MainWidget::stickersBox(const MTPInputStickerSet &set) { Messenger::Instance().hideMediaView(); auto box = Ui::show(Box(set)); - connect(box, SIGNAL(installed(uint64)), this, SLOT(onStickersInstalled(uint64))); + connect(box, SIGNAL(installed(uint64_t)), this, SLOT(onStickersInstalled(uint64_t))); } -void MainWidget::onStickersInstalled(uint64 setId) { +void MainWidget::onStickersInstalled(uint64_t setId) { _history->stickersInstalled(setId); } @@ -4215,7 +4211,7 @@ void MainWidget::applyNotifySetting(const MTPNotifyPeer &peer, const MTPPeerNoti setTo->sound = sound; if (updatePeer) { if (!h) h = App::history(updatePeer->id); - int32 changeIn = 0; + int32_t changeIn = 0; if (isNotifyMuted(setTo, &changeIn)) { Auth().notifications().clearFromHistory(h); h->setMute(true); @@ -4366,7 +4362,7 @@ void MainWidget::destroyData() { _dialogs->destroyData(); } -void MainWidget::updateOnlineDisplayIn(int32 msecs) { +void MainWidget::updateOnlineDisplayIn(int32_t msecs) { _onlineUpdater.start(msecs); } @@ -4390,7 +4386,7 @@ TimeMs MainWidget::lastSetOnline() const { return _lastSetOnline; } -int32 MainWidget::dlgsWidth() const { +int32_t MainWidget::dlgsWidth() const { return _dialogs->width(); } @@ -4629,7 +4625,7 @@ DataIsLoadedResult allDataLoadedForMessage(const MTPMessage &msg) { } // namespace -void MainWidget::feedUpdates(const MTPUpdates &updates, uint64 randomId) { +void MainWidget::feedUpdates(const MTPUpdates &updates, uint64_t randomId) { switch (updates.type()) { case mtpc_updates: { auto &d = updates.c_updates(); @@ -5305,7 +5301,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) { } auto &order(Global::RefStickerSetsOrder()); - int32 insertAtIndex = 0, currentIndex = order.indexOf(s.vid.v); + int32_t insertAtIndex = 0, currentIndex = order.indexOf(s.vid.v); if (currentIndex != insertAtIndex) { if (currentIndex > 0) { order.removeAt(currentIndex); @@ -5315,8 +5311,8 @@ void MainWidget::feedUpdate(const MTPUpdate &update) { auto custom = sets.find(Stickers::CustomSetId); if (custom != sets.cend()) { - for (int32 i = 0, l = it->stickers.size(); i < l; ++i) { - int32 removeIndex = custom->stickers.indexOf(it->stickers.at(i)); + for (int32_t i = 0, l = it->stickers.size(); i < l; ++i) { + int32_t removeIndex = custom->stickers.indexOf(it->stickers.at(i)); if (removeIndex >= 0) custom->stickers.removeAt(removeIndex); } if (custom->stickers.isEmpty()) { diff --git a/Telegram/SourceFiles/mainwidget.h b/Telegram/SourceFiles/mainwidget.h index af50b0f2e..8875187e4 100644 --- a/Telegram/SourceFiles/mainwidget.h +++ b/Telegram/SourceFiles/mainwidget.h @@ -120,7 +120,7 @@ private: class StackItemOverview : public StackItem { public: - StackItemOverview(PeerData *peer, MediaOverviewType mediaType, int32 lastWidth, int32 lastScrollTop) : StackItem(peer) + StackItemOverview(PeerData *peer, MediaOverviewType mediaType, int32_t lastWidth, int32_t lastScrollTop) : StackItem(peer) , mediaType(mediaType) , lastWidth(lastWidth) , lastScrollTop(lastScrollTop) { @@ -129,7 +129,7 @@ public: return OverviewStackItem; } MediaOverviewType mediaType; - int32 lastWidth, lastScrollTop; + int32_t lastWidth, lastScrollTop; }; enum SilentNotifiesStatus { @@ -189,7 +189,7 @@ public: void windowShown(); - void sentUpdatesReceived(uint64 randomId, const MTPUpdates &updates); + void sentUpdatesReceived(uint64_t randomId, const MTPUpdates &updates); void sentUpdatesReceived(const MTPUpdates &updates) { return sentUpdatesReceived(0, updates); } @@ -212,7 +212,7 @@ public: PeerData *overviewPeer(); bool showMediaTypeSwitch() const; void showWideSection(Window::SectionMemento &&memento); - void showMediaOverview(PeerData *peer, MediaOverviewType type, bool back = false, int32 lastScrollTop = -1); + void showMediaOverview(PeerData *peer, MediaOverviewType type, bool back = false, int32_t lastScrollTop = -1); bool stackIsEmpty() const; void showBackFromStack(); void orderWidgets(); @@ -223,7 +223,7 @@ public: bool onSendSticker(DocumentData *sticker); void destroyData(); - void updateOnlineDisplayIn(int32 msecs); + void updateOnlineDisplayIn(int32_t msecs); bool isActive() const; bool doWeReadServerHistory() const; @@ -235,7 +235,7 @@ public: void applyCloudDraft(History *history); void writeDrafts(History *history); - int32 dlgsWidth() const; + int32_t dlgsWidth() const; void showForwardLayer(const SelectedItemSet &items); void showSendPathsLayer(); @@ -324,7 +324,7 @@ public: void checkLastUpdate(bool afterSleep); - void insertCheckedServiceNotification(const TextWithEntities &message, const MTPMessageMedia &media, int32 date); + void insertCheckedServiceNotification(const TextWithEntities &message, const MTPMessageMedia &media, int32_t date); void serviceHistoryDone(const MTPmessages_Messages &msgs); bool serviceHistoryFail(const RPCError &error); @@ -335,7 +335,7 @@ public: void setChatBackground(const App::WallPaper &wp); bool chatBackgroundLoading(); - float64 chatBackgroundProgress() const; + double chatBackgroundProgress() const; void checkChatBackground(); ImagePtr newBackgroundThumb(); @@ -353,13 +353,13 @@ public: void webPageUpdated(WebPageData *page); void gameUpdated(GameData *game); - void updateMutedIn(int32 seconds); + void updateMutedIn(int32_t seconds); void choosePeer(PeerId peerId, MsgId showAtMsgId); // does offerPeer or showPeerHistory void clearBotStartToken(PeerData *peer); - void ptsWaiterStartTimerFor(ChannelData *channel, int32 ms); // ms <= 0 - stop timer - void feedUpdates(const MTPUpdates &updates, uint64 randomId = 0); + void ptsWaiterStartTimerFor(ChannelData *channel, int32_t ms); // ms <= 0 - stop timer + void feedUpdates(const MTPUpdates &updates, uint64_t randomId = 0); void feedUpdate(const MTPUpdate &update); void ctrlEnterSubmitUpdated(); @@ -385,7 +385,7 @@ public: void app_sendBotCallback(const HistoryMessageReplyMarkup::Button *button, const HistoryItem *msg, int row, int col); void ui_repaintHistoryItem(not_null item); - void ui_showPeerHistory(quint64 peer, qint32 msgId, Ui::ShowWay way); + void ui_showPeerHistory(uint64_t peer, int32_t msgId, Ui::ShowWay way); PeerData *ui_getPeerForMouseAction(); void notify_botCommandsChanged(UserData *bot); @@ -440,12 +440,12 @@ public slots: void onUpdateMuted(); - void onStickersInstalled(uint64 setId); + void onStickersInstalled(uint64_t setId); void onViewsIncrement(); - void ui_showPeerHistoryAsync(quint64 peerId, qint32 showAtMsgId, Ui::ShowWay way); - void ui_autoplayMediaInlineAsync(qint32 channelId, qint32 msgId); + void ui_showPeerHistoryAsync(uint64_t peerId, int32_t showAtMsgId, Ui::ShowWay way); + void ui_autoplayMediaInlineAsync(int32_t channelId, int32_t msgId); protected: void paintEvent(QPaintEvent *e) override; @@ -536,7 +536,7 @@ private: bool failDifference(const RPCError &e); void feedDifference(const MTPVector &users, const MTPVector &chats, const MTPVector &msgs, const MTPVector &other); void gotState(const MTPupdates_State &state); - void updSetState(int32 pts, int32 date, int32 qts, int32 seq); + void updSetState(int32_t pts, int32_t date, int32_t qts, int32_t seq); void gotChannelDifference(ChannelData *channel, const MTPupdates_ChannelDifference &diff); bool failChannelDifference(ChannelData *channel, const RPCError &err); void failDifferenceStartTimerFor(ChannelData *channel); @@ -582,10 +582,10 @@ private: QPoint getFloatPlayerHiddenPosition(QPoint position, QSize size, RectPart side) const; RectPart getFloatPlayerSide(QPoint center) const; - bool ptsUpdateAndApply(int32 pts, int32 ptsCount, const MTPUpdates &updates); - bool ptsUpdateAndApply(int32 pts, int32 ptsCount, const MTPUpdate &update); - bool ptsUpdateAndApply(int32 pts, int32 ptsCount); - bool getDifferenceTimeChanged(ChannelData *channel, int32 ms, ChannelGetDifferenceTime &channelCurTime, TimeMs &curTime); + bool ptsUpdateAndApply(int32_t pts, int32_t ptsCount, const MTPUpdates &updates); + bool ptsUpdateAndApply(int32_t pts, int32_t ptsCount, const MTPUpdate &update); + bool ptsUpdateAndApply(int32_t pts, int32_t ptsCount); + bool getDifferenceTimeChanged(ChannelData *channel, int32_t ms, ChannelGetDifferenceTime &channelCurTime, TimeMs &curTime); void viewsIncrementDone(QVector ids, const MTPVector &result, mtpRequestId req); bool viewsIncrementFail(const RPCError &error, mtpRequestId req); @@ -636,9 +636,9 @@ private: int _callTopBarHeight = 0; int _contentScrollAddToY = 0; - int32 updDate = 0; - int32 updQts = -1; - int32 updSeq = 0; + int32_t updDate = 0; + int32_t updQts = -1; + int32_t updSeq = 0; SingleTimer noUpdatesTimer; PtsWaiter _ptsWaiter; @@ -649,7 +649,7 @@ private: SingleTimer _byPtsTimer; - QMap _bySeqUpdates; + QMap _bySeqUpdates; SingleTimer _bySeqTimer; SingleTimer _byMinChannelTimer; @@ -671,8 +671,8 @@ private: typedef QMap OverviewsPreload; OverviewsPreload _overviewPreload[OverviewCount], _overviewLoad[OverviewCount]; - int32 _failDifferenceTimeout = 1; // growing timeout for getDifference calls, if it fails - typedef QMap ChannelFailDifferenceTimeout; + int32_t _failDifferenceTimeout = 1; // growing timeout for getDifference calls, if it fails + typedef QMap ChannelFailDifferenceTimeout; ChannelFailDifferenceTimeout _channelFailDifferenceTimeout; // growing timeout for getChannelDifference calls, if it fails SingleTimer _failDifferenceTimer; diff --git a/Telegram/SourceFiles/mainwindow.cpp b/Telegram/SourceFiles/mainwindow.cpp index 00682cbea..eff943c5d 100644 --- a/Telegram/SourceFiles/mainwindow.cpp +++ b/Telegram/SourceFiles/mainwindow.cpp @@ -42,7 +42,6 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "boxes/add_contact_box.h" #include "boxes/connection_box.h" #include "observer_peer.h" -#include "autoupdater.h" #include "mediaview.h" #include "storage/localstorage.h" #include "apiwrap.h" @@ -86,7 +85,7 @@ ConnectingWidget::ConnectingWidget(QWidget *parent, const QString &text, const Q void ConnectingWidget::set(const QString &text, const QString &reconnect) { _text = text; _textWidth = st::linkFont->width(_text) + st::linkFont->spacew; - int32 _reconnectWidth = 0; + int32_t _reconnectWidth = 0; if (reconnect.isEmpty()) { _reconnect->hide(); } else { @@ -265,7 +264,7 @@ void MainWindow::setupIntro() { } } -void MainWindow::serviceNotification(const TextWithEntities &message, const MTPMessageMedia &media, int32 date, bool force) { +void MainWindow::serviceNotification(const TextWithEntities &message, const MTPMessageMedia &media, int32_t date, bool force) { if (date <= 0) date = unixtime(); auto h = (_main && App::userLoaded(ServiceUserId)) ? App::history(ServiceUserId).get() : nullptr; if (!h || (!force && h->isEmpty())) { @@ -366,7 +365,7 @@ void MainWindow::ui_hideSettingsAndLayer(ShowLayerOptions options) { } } -void MainWindow::mtpStateChanged(int32 dc, int32 state) { +void MainWindow::mtpStateChanged(int32_t dc, int32_t state) { if (dc == MTP::maindc()) { updateConnectingStatus(); Global::RefConnectionTypeChanged().notify(); @@ -854,12 +853,12 @@ void MainWindow::placeSmallCounter(QImage &img, int size, int count, style::colo QPainter p(&img); QString cnt = (count < 100) ? QString("%1").arg(count) : QString("..%1").arg(count % 10, 1, 10, QChar('0')); - int32 cntSize = cnt.size(); + int32_t cntSize = cnt.size(); p.setBrush(bg->b); p.setPen(Qt::NoPen); p.setRenderHint(QPainter::Antialiasing); - int32 fontSize; + int32_t fontSize; if (size == 16) { fontSize = 8; } else if (size == 32) { @@ -868,7 +867,7 @@ void MainWindow::placeSmallCounter(QImage &img, int size, int count, style::colo fontSize = (cntSize < 2) ? 22 : 22; } style::font f = { fontSize, 0, 0 }; - int32 w = f->width(cnt), d, r; + int32_t w = f->width(cnt), d, r; if (size == 16) { d = (cntSize < 2) ? 2 : 1; r = (cntSize < 2) ? 4 : 3; @@ -899,14 +898,14 @@ QImage MainWindow::iconWithCounter(int size, int count, style::color bg, style:: QString cnt = (count < 1000) ? QString("%1").arg(count) : QString("..%1").arg(count % 100, 2, 10, QChar('0')); QImage result(size, size, QImage::Format_ARGB32); - int32 cntSize = cnt.size(); + int32_t cntSize = cnt.size(); result.fill(Qt::transparent); { QPainter p(&result); p.setBrush(bg); p.setPen(Qt::NoPen); p.setRenderHint(QPainter::Antialiasing); - int32 fontSize; + int32_t fontSize; if (size == 16) { fontSize = (cntSize < 2) ? 11 : ((cntSize < 3) ? 11 : 8); } else if (size == 20) { @@ -917,7 +916,7 @@ QImage MainWindow::iconWithCounter(int size, int count, style::color bg, style:: fontSize = (cntSize < 2) ? 22 : ((cntSize < 3) ? 20 : 16); } style::font f = { fontSize, 0, 0 }; - int32 w = f->width(cnt), d, r; + int32_t w = f->width(cnt), d, r; if (size == 16) { d = (cntSize < 2) ? 5 : ((cntSize < 3) ? 2 : 1); r = (cntSize < 2) ? 8 : ((cntSize < 3) ? 7 : 3); @@ -1181,10 +1180,6 @@ LastCrashedWindow::LastCrashedWindow() , _sendingTotal(0) , _checkReply(0) , _sendReply(0) -#ifndef TDESKTOP_DISABLE_AUTOUPDATE -, _updatingCheck(this) -, _updatingSkip(this, false) -#endif // !TDESKTOP_DISABLE_AUTOUPDATE { excludeReportUsername(); @@ -1192,7 +1187,7 @@ LastCrashedWindow::LastCrashedWindow() _sendingState = SendingNoReport; } if (_sendingState != SendingNoReport) { - qint64 dumpsize = 0; + int64_t dumpsize = 0; QString dumpspath = cWorkingDir() + qsl("tdata/dumps"); #if defined Q_OS_MAC && !defined MAC_USE_BREAKPAD dumpspath += qsl("/completed"); @@ -1216,7 +1211,7 @@ LastCrashedWindow::LastCrashedWindow() QString maxDump, maxDumpFull; QDateTime maxDumpModified, workingModified = QFileInfo(cWorkingDir() + qsl("tdata/working")).lastModified(); QFileInfoList list = QDir(dumpspath).entryInfoList(); - for (int32 i = 0, l = list.size(); i < l; ++i) { + for (int32_t i = 0, l = list.size(); i < l; ++i) { QString name = list.at(i).fileName(); if (name.endsWith(qstr(".dmp"))) { QDateTime modified = list.at(i).lastModified(); @@ -1256,35 +1251,10 @@ LastCrashedWindow::LastCrashedWindow() _label.setText(qsl("Last time Telegram Desktop crashed :(")); } -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - _updatingCheck.setText(qsl("TRY AGAIN")); - connect(&_updatingCheck, SIGNAL(clicked()), this, SLOT(onUpdateRetry())); - _updatingSkip.setText(qsl("SKIP")); - connect(&_updatingSkip, SIGNAL(clicked()), this, SLOT(onUpdateSkip())); - - Sandbox::connect(SIGNAL(updateChecking()), this, SLOT(onUpdateChecking())); - Sandbox::connect(SIGNAL(updateLatest()), this, SLOT(onUpdateLatest())); - Sandbox::connect(SIGNAL(updateProgress(qint64,qint64)), this, SLOT(onUpdateDownloading(qint64,qint64))); - Sandbox::connect(SIGNAL(updateFailed()), this, SLOT(onUpdateFailed())); - Sandbox::connect(SIGNAL(updateReady()), this, SLOT(onUpdateReady())); - - switch (Sandbox::updatingState()) { - case Application::UpdatingDownload: - setUpdatingState(UpdatingDownload, true); - setDownloadProgress(Sandbox::updatingReady(), Sandbox::updatingSize()); - break; - case Application::UpdatingReady: setUpdatingState(UpdatingReady, true); break; - default: setUpdatingState(UpdatingCheck, true); break; - } - - cSetLastUpdateCheck(0); - Sandbox::startUpdateCheck(); -#else // !TDESKTOP_DISABLE_AUTOUPDATE _updating.setText(qsl("Please check if there is a new version available.")); if (_sendingState != SendingNoReport) { _sendingState = SendingNone; } -#endif // else for !TDESKTOP_DISABLE_AUTOUPDATE _pleaseSendReport.setText(qsl("Please send us a crash report.")); _yourReportName.setText(qsl("Your Report Tag: %1\nYour User Tag: %2").arg(QString(_minidumpName).replace(".dmp", "")).arg(Sandbox::UserTag(), 0, 16)); @@ -1348,7 +1318,7 @@ void LastCrashedWindow::onGetApp() { void LastCrashedWindow::excludeReportUsername() { QString prefix = qstr("Username:"); QStringList lines = _reportText.split('\n'); - for (int32 i = 0, l = lines.size(); i < l; ++i) { + for (int32_t i = 0, l = lines.size(); i < l; ++i) { if (lines.at(i).trimmed().startsWith(prefix)) { _reportUsername = lines.at(i).trimmed().mid(prefix.size()).trimmed(); lines.removeAt(i); @@ -1360,7 +1330,7 @@ void LastCrashedWindow::excludeReportUsername() { QString LastCrashedWindow::getReportField(const QLatin1String &name, const QLatin1String &prefix) { QStringList lines = _reportText.split('\n'); - for (int32 i = 0, l = lines.size(); i < l; ++i) { + for (int32_t i = 0, l = lines.size(); i < l; ++i) { if (lines.at(i).trimmed().startsWith(prefix)) { QString data = lines.at(i).trimmed().mid(prefix.size()).trimmed(); @@ -1494,7 +1464,7 @@ void LastCrashedWindow::onCheckingFinished() { connect(_sendReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onSendingError(QNetworkReply::NetworkError))); connect(_sendReply, SIGNAL(finished()), this, SLOT(onSendingFinished())); - connect(_sendReply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(onSendingProgress(qint64,qint64))); + connect(_sendReply, SIGNAL(uploadProgress(int64_t,int64_t)), this, SLOT(onSendingProgress(int64_t,int64_t))); updateControls(); } @@ -1503,139 +1473,6 @@ void LastCrashedWindow::updateControls() { int padding = _size, h = padding + _networkSettings.height() + padding; _label.show(); -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - h += _networkSettings.height() + padding; - if (_updatingState == UpdatingFail && (_sendingState == SendingNoReport || _sendingState == SendingUpdateCheck)) { - _networkSettings.show(); - _updatingCheck.show(); - _updatingSkip.show(); - _send.hide(); - _sendSkip.hide(); - _continue.hide(); - _pleaseSendReport.hide(); - _yourReportName.hide(); - _includeUsername.hide(); - _getApp.hide(); - _showReport.hide(); - _report.hide(); - _minidump.hide(); - _saveReport.hide(); - h += padding + _updatingCheck.height() + padding; - } else { - if (_updatingState == UpdatingCheck || _sendingState == SendingFail || _sendingState == SendingProgress) { - _networkSettings.show(); - } else { - _networkSettings.hide(); - } - if (_updatingState == UpdatingNone || _updatingState == UpdatingLatest || _updatingState == UpdatingFail) { - h += padding + _updatingCheck.height() + padding; - if (_sendingState == SendingNoReport) { - _pleaseSendReport.hide(); - _yourReportName.hide(); - _includeUsername.hide(); - _getApp.hide(); - _showReport.hide(); - _report.hide(); - _minidump.hide(); - _saveReport.hide(); - _send.hide(); - _sendSkip.hide(); - _continue.show(); - } else { - h += _showReport.height() + padding + _yourReportName.height() + padding; - _pleaseSendReport.show(); - _yourReportName.show(); - if (_reportUsername.isEmpty()) { - _includeUsername.hide(); - } else { - h += _includeUsername.height() + padding; - _includeUsername.show(); - } - if (_sendingState == SendingTooOld || _sendingState == SendingUnofficial) { - QString verStr = getReportField(qstr("version"), qstr("Version:")); - qint64 ver = verStr.isEmpty() ? 0 : verStr.toLongLong(); - if (!ver || (ver == AppVersion) || (ver < 0 && (-ver / 1000) == AppVersion)) { - h += _getApp.height() + padding; - _getApp.show(); - h -= _yourReportName.height() + padding; // hide report name - _yourReportName.hide(); - if (!_reportUsername.isEmpty()) { - h -= _includeUsername.height() + padding; - _includeUsername.hide(); - } - } else { - _getApp.hide(); - } - _showReport.hide(); - _report.hide(); - _minidump.hide(); - _saveReport.hide(); - _send.hide(); - _sendSkip.hide(); - _continue.show(); - } else { - _getApp.hide(); - if (_reportShown) { - h += (_pleaseSendReport.height() * 12.5) + padding + (_minidumpName.isEmpty() ? 0 : (_minidump.height() + padding)); - _report.show(); - if (_minidumpName.isEmpty()) { - _minidump.hide(); - } else { - _minidump.show(); - } - if (_reportSaved || _sendingState == SendingFail || _sendingState == SendingProgress || _sendingState == SendingUploading) { - _saveReport.hide(); - } else { - _saveReport.show(); - } - _showReport.hide(); - } else { - _report.hide(); - _minidump.hide(); - _saveReport.hide(); - if (_sendingState == SendingFail || _sendingState == SendingProgress || _sendingState == SendingUploading) { - _showReport.hide(); - } else { - _showReport.show(); - } - } - if (_sendingState == SendingTooMany || _sendingState == SendingDone) { - _send.hide(); - _sendSkip.hide(); - _continue.show(); - } else { - if (_sendingState == SendingProgress || _sendingState == SendingUploading) { - _send.hide(); - } else { - _send.show(); - } - _sendSkip.show(); - _continue.hide(); - } - } - } - } else { - _getApp.hide(); - _pleaseSendReport.hide(); - _yourReportName.hide(); - _includeUsername.hide(); - _showReport.hide(); - _report.hide(); - _minidump.hide(); - _saveReport.hide(); - _send.hide(); - _sendSkip.hide(); - _continue.hide(); - } - _updatingCheck.hide(); - if (_updatingState == UpdatingCheck || _updatingState == UpdatingDownload) { - h += padding + _updatingSkip.height() + padding; - _updatingSkip.show(); - } else { - _updatingSkip.hide(); - } - } -#else // !TDESKTOP_DISABLE_AUTOUPDATE h += _networkSettings.height() + padding; h += padding + _send.height() + padding; if (_sendingState == SendingNoReport) { @@ -1707,7 +1544,6 @@ void LastCrashedWindow::updateControls() { _getApp.show(); h += _networkSettings.height() + padding; -#endif // else for !TDESKTOP_DISABLE_AUTOUPDATE QRect scr(QApplication::primaryScreen()->availableGeometry()); QSize s(2 * padding + QFontMetrics(_label.font()).width(qsl("Last time Telegram Desktop was not closed properly.")) + padding + _networkSettings.width(), h); @@ -1721,114 +1557,21 @@ void LastCrashedWindow::updateControls() { void LastCrashedWindow::onNetworkSettings() { auto &p = Sandbox::PreLaunchProxy(); NetworkSettingsWindow *box = new NetworkSettingsWindow(this, p.host, p.port ? p.port : 80, p.user, p.password); - connect(box, SIGNAL(saved(QString, quint32, QString, QString)), this, SLOT(onNetworkSettingsSaved(QString, quint32, QString, QString))); + connect(box, SIGNAL(saved(QString, uint32_t, QString, QString)), this, SLOT(onNetworkSettingsSaved(QString, uint32_t, QString, QString))); box->show(); } -void LastCrashedWindow::onNetworkSettingsSaved(QString host, quint32 port, QString username, QString password) { +void LastCrashedWindow::onNetworkSettingsSaved(QString host, uint32_t port, QString username, QString password) { Sandbox::RefPreLaunchProxy().host = host; Sandbox::RefPreLaunchProxy().port = port ? port : 80; Sandbox::RefPreLaunchProxy().user = username; Sandbox::RefPreLaunchProxy().password = password; -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - if ((_updatingState == UpdatingFail && (_sendingState == SendingNoReport || _sendingState == SendingUpdateCheck)) || (_updatingState == UpdatingCheck)) { - Sandbox::stopUpdate(); - cSetLastUpdateCheck(0); - Sandbox::startUpdateCheck(); - } else -#endif // !TDESKTOP_DISABLE_AUTOUPDATE if (_sendingState == SendingFail || _sendingState == SendingProgress) { onSendReport(); } activate(); } -#ifndef TDESKTOP_DISABLE_AUTOUPDATE -void LastCrashedWindow::setUpdatingState(UpdatingState state, bool force) { - if (_updatingState != state || force) { - _updatingState = state; - switch (state) { - case UpdatingLatest: - _updating.setText(qsl("Latest version is installed.")); - if (_sendingState == SendingNoReport) { - QTimer::singleShot(0, this, SLOT(onContinue())); - } else { - _sendingState = SendingNone; - } - break; - case UpdatingReady: - if (checkReadyUpdate()) { - cSetRestartingUpdate(true); - App::quit(); - return; - } else { - setUpdatingState(UpdatingFail); - return; - } - break; - case UpdatingCheck: - _updating.setText(qsl("Checking for updates...")); - break; - case UpdatingFail: - _updating.setText(qsl("Update check failed :(")); - break; - } - updateControls(); - } -} - -void LastCrashedWindow::setDownloadProgress(qint64 ready, qint64 total) { - qint64 readyTenthMb = (ready * 10 / (1024 * 1024)), totalTenthMb = (total * 10 / (1024 * 1024)); - QString readyStr = QString::number(readyTenthMb / 10) + '.' + QString::number(readyTenthMb % 10); - QString totalStr = QString::number(totalTenthMb / 10) + '.' + QString::number(totalTenthMb % 10); - QString res = qsl("Downloading update {ready} / {total} MB..").replace(qstr("{ready}"), readyStr).replace(qstr("{total}"), totalStr); - if (_newVersionDownload != res) { - _newVersionDownload = res; - _updating.setText(_newVersionDownload); - updateControls(); - } -} - -void LastCrashedWindow::onUpdateRetry() { - cSetLastUpdateCheck(0); - Sandbox::startUpdateCheck(); -} - -void LastCrashedWindow::onUpdateSkip() { - if (_sendingState == SendingNoReport) { - onContinue(); - } else { - if (_updatingState == UpdatingCheck || _updatingState == UpdatingDownload) { - Sandbox::stopUpdate(); - setUpdatingState(UpdatingFail); - } - _sendingState = SendingNone; - updateControls(); - } -} - -void LastCrashedWindow::onUpdateChecking() { - setUpdatingState(UpdatingCheck); -} - -void LastCrashedWindow::onUpdateLatest() { - setUpdatingState(UpdatingLatest); -} - -void LastCrashedWindow::onUpdateDownloading(qint64 ready, qint64 total) { - setUpdatingState(UpdatingDownload); - setDownloadProgress(ready, total); -} - -void LastCrashedWindow::onUpdateReady() { - setUpdatingState(UpdatingReady); -} - -void LastCrashedWindow::onUpdateFailed() { - setUpdatingState(UpdatingFail); -} -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - void LastCrashedWindow::onContinue() { if (SignalHandlers::restart() == SignalHandlers::CantOpen) { new NotStartedWindow(); @@ -1869,7 +1612,7 @@ void LastCrashedWindow::onSendingFinished() { } } -void LastCrashedWindow::onSendingProgress(qint64 uploaded, qint64 total) { +void LastCrashedWindow::onSendingProgress(int64_t uploaded, int64_t total) { if (_sendingState != SendingProgress && _sendingState != SendingUploading) return; _sendingState = SendingUploading; @@ -1898,27 +1641,6 @@ void LastCrashedWindow::resizeEvent(QResizeEvent *e) { _updating.move(padding, padding * 2 + _networkSettings.height() + (_networkSettings.height() - _updating.height()) / 2); -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - _pleaseSendReport.move(padding, padding * 2 + _networkSettings.height() + _networkSettings.height() + padding + (_showReport.height() - _pleaseSendReport.height()) / 2); - _showReport.move(padding * 2 + _pleaseSendReport.width(), padding * 2 + _networkSettings.height() + _networkSettings.height() + padding); - _yourReportName.move(padding, _showReport.y() + _showReport.height() + padding); - _includeUsername.move(padding, _yourReportName.y() + _yourReportName.height() + padding); - _getApp.move((width() - _getApp.width()) / 2, _showReport.y() + _showReport.height() + padding); - - if (_sendingState == SendingFail || _sendingState == SendingProgress) { - _networkSettings.move(padding * 2 + _pleaseSendReport.width(), padding * 2 + _networkSettings.height() + _networkSettings.height() + padding); - } else { - _networkSettings.move(padding * 2 + _updating.width(), padding * 2 + _networkSettings.height()); - } - - if (_updatingState == UpdatingCheck || _updatingState == UpdatingDownload) { - _updatingCheck.move(width() - padding - _updatingCheck.width(), height() - padding - _updatingCheck.height()); - _updatingSkip.move(width() - padding - _updatingSkip.width(), height() - padding - _updatingSkip.height()); - } else { - _updatingCheck.move(width() - padding - _updatingCheck.width(), height() - padding - _updatingCheck.height()); - _updatingSkip.move(width() - padding - _updatingCheck.width() - padding - _updatingSkip.width(), height() - padding - _updatingSkip.height()); - } -#else // !TDESKTOP_DISABLE_AUTOUPDATE _getApp.move((width() - _getApp.width()) / 2, _updating.y() + _updating.height() + padding); _pleaseSendReport.move(padding, padding * 2 + _networkSettings.height() + _networkSettings.height() + padding + _getApp.height() + padding + (_showReport.height() - _pleaseSendReport.height()) / 2); @@ -1927,7 +1649,7 @@ void LastCrashedWindow::resizeEvent(QResizeEvent *e) { _includeUsername.move(padding, _yourReportName.y() + _yourReportName.height() + padding); _networkSettings.move(padding * 2 + _pleaseSendReport.width(), padding * 2 + _networkSettings.height() + _networkSettings.height() + padding + _getApp.height() + padding); -#endif // else for !TDESKTOP_DISABLE_AUTOUPDATE + if (_reportUsername.isEmpty()) { _report.setGeometry(padding, _yourReportName.y() + _yourReportName.height() + padding, width() - 2 * padding, _pleaseSendReport.height() * 12.5); } else { @@ -1939,7 +1661,7 @@ void LastCrashedWindow::resizeEvent(QResizeEvent *e) { _continue.move(width() - padding - _continue.width(), height() - padding - _continue.height()); } -NetworkSettingsWindow::NetworkSettingsWindow(QWidget *parent, QString host, quint32 port, QString username, QString password) +NetworkSettingsWindow::NetworkSettingsWindow(QWidget *parent, QString host, uint32_t port, QString username, QString password) : PreLaunchWindow(qsl("HTTP Proxy Settings")) , _hostLabel(this) , _portLabel(this) diff --git a/Telegram/SourceFiles/mainwindow.h b/Telegram/SourceFiles/mainwindow.h index b116b9c09..003d06c59 100644 --- a/Telegram/SourceFiles/mainwindow.h +++ b/Telegram/SourceFiles/mainwindow.h @@ -83,11 +83,11 @@ public: void clearPasscode(); void setupIntro(); void setupMain(const MTPUser *user = nullptr); - void serviceNotification(const TextWithEntities &message, const MTPMessageMedia &media = MTP_messageMediaEmpty(), int32 date = 0, bool force = false); + void serviceNotification(const TextWithEntities &message, const MTPMessageMedia &media = MTP_messageMediaEmpty(), int32_t date = 0, bool force = false); void sendServiceHistoryRequest(); void showDelayedServiceMsgs(); - void mtpStateChanged(int32 dc, int32 state); + void mtpStateChanged(int32_t dc, int32_t state); MainWidget *mainWidget(); PasscodeWidget *passcodeWidget(); @@ -188,11 +188,11 @@ private: QImage icon16, icon32, icon64, iconbig16, iconbig32, iconbig64; struct DelayedServiceMsg { - DelayedServiceMsg(const TextWithEntities &message, const MTPMessageMedia &media, int32 date) : message(message), media(media), date(date) { + DelayedServiceMsg(const TextWithEntities &message, const MTPMessageMedia &media, int32_t date) : message(message), media(media), date(date) { } TextWithEntities message; MTPMessageMedia media; - int32 date; + int32_t date; }; QList _delayedServiceMsgs; mtpRequestId _serviceHistoryRequest = 0; @@ -291,24 +291,13 @@ public slots: void onGetApp(); void onNetworkSettings(); - void onNetworkSettingsSaved(QString host, quint32 port, QString username, QString password); + void onNetworkSettingsSaved(QString host, uint32_t port, QString username, QString password); void onContinue(); void onCheckingFinished(); void onSendingError(QNetworkReply::NetworkError e); void onSendingFinished(); - void onSendingProgress(qint64 uploaded, qint64 total); - -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - void onUpdateRetry(); - void onUpdateSkip(); - - void onUpdateChecking(); - void onUpdateLatest(); - void onUpdateDownloading(qint64 ready, qint64 total); - void onUpdateReady(); - void onUpdateFailed(); -#endif // !TDESKTOP_DISABLE_AUTOUPDATE + void onSendingProgress(int64_t uploaded, int64_t total); protected: @@ -321,7 +310,7 @@ private: void updateControls(); QString _host, _username, _password; - quint32 _port; + uint32_t _port; PreLaunchLabel _label, _pleaseSendReport, _yourReportName, _minidump; PreLaunchLog _report; @@ -351,28 +340,11 @@ private: SendingState _sendingState; PreLaunchLabel _updating; - qint64 _sendingProgress, _sendingTotal; + int64_t _sendingProgress, _sendingTotal; QNetworkAccessManager _sendManager; QNetworkReply *_checkReply, *_sendReply; -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - PreLaunchButton _updatingCheck, _updatingSkip; - enum UpdatingState { - UpdatingNone, - UpdatingCheck, - UpdatingLatest, - UpdatingDownload, - UpdatingFail, - UpdatingReady - }; - UpdatingState _updatingState; - QString _newVersionDownload; - - void setUpdatingState(UpdatingState state, bool force = false); - void setDownloadProgress(qint64 ready, qint64 total); -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - QString getReportField(const QLatin1String &name, const QLatin1String &prefix); void addReportFieldPart(const QLatin1String &name, const QLatin1String &prefix, QHttpMultiPart *multipart); @@ -383,11 +355,11 @@ class NetworkSettingsWindow : public PreLaunchWindow { public: - NetworkSettingsWindow(QWidget *parent, QString host, quint32 port, QString username, QString password); + NetworkSettingsWindow(QWidget *parent, QString host, uint32_t port, QString username, QString password); signals: - void saved(QString host, quint32 port, QString username, QString password); + void saved(QString host, uint32_t port, QString username, QString password); public slots: diff --git a/Telegram/SourceFiles/media/media_audio.cpp b/Telegram/SourceFiles/media/media_audio.cpp index b0a1ade1e..10262859f 100644 --- a/Telegram/SourceFiles/media/media_audio.cpp +++ b/Telegram/SourceFiles/media/media_audio.cpp @@ -270,7 +270,7 @@ base::Observable &Updated() { } // Thread: Any. Must be locked: AudioMutex. -float64 ComputeVolume(AudioMsgId::Type type) { +double ComputeVolume(AudioMsgId::Type type) { switch (type) { case AudioMsgId::Type::Voice: return VolumeMultiplierAll; case AudioMsgId::Type::Song: return VolumeMultiplierSong * mixer()->getSongVolume(); @@ -449,14 +449,14 @@ Mixer::Mixer() connect(this, SIGNAL(faderOnTimer()), _fader, SLOT(onTimer()), Qt::QueuedConnection); connect(this, SIGNAL(suppressSong()), _fader, SLOT(onSuppressSong())); connect(this, SIGNAL(unsuppressSong()), _fader, SLOT(onUnsuppressSong())); - connect(this, SIGNAL(suppressAll(qint64)), _fader, SLOT(onSuppressAll(qint64))); + connect(this, SIGNAL(suppressAll(int64_t)), _fader, SLOT(onSuppressAll(int64_t))); subscribe(Global::RefSongVolumeChanged(), [this] { QMetaObject::invokeMethod(_fader, "onSongVolumeChanged"); }); subscribe(Global::RefVideoVolumeChanged(), [this] { QMetaObject::invokeMethod(_fader, "onVideoVolumeChanged"); }); - connect(this, SIGNAL(loaderOnStart(const AudioMsgId&, qint64)), _loader, SLOT(onStart(const AudioMsgId&, qint64))); + connect(this, SIGNAL(loaderOnStart(const AudioMsgId&, int64_t)), _loader, SLOT(onStart(const AudioMsgId&, int64_t))); connect(this, SIGNAL(loaderOnCancel(const AudioMsgId&)), _loader, SLOT(onCancel(const AudioMsgId&))); connect(_loader, SIGNAL(needToCheck()), _fader, SLOT(onTimer())); connect(_loader, SIGNAL(error(const AudioMsgId&)), this, SLOT(onError(const AudioMsgId&))); @@ -614,12 +614,12 @@ bool Mixer::fadedStop(AudioMsgId::Type type, bool *fadedStart) { return false; } -void Mixer::play(const AudioMsgId &audio, int64 position) { +void Mixer::play(const AudioMsgId &audio, int64_t position) { setSongVolume(Global::SongVolume()); play(audio, nullptr, position); } -void Mixer::play(const AudioMsgId &audio, std::unique_ptr videoData, int64 position) { +void Mixer::play(const AudioMsgId &audio, std::unique_ptr videoData, int64_t position) { Expects(!videoData || audio.playId() != 0); auto type = audio.type(); @@ -866,7 +866,7 @@ void Mixer::resume(const AudioMsgId &audio, bool fast) { if (current) emit updated(current); } -void Mixer::seek(AudioMsgId::Type type, int64 position) { +void Mixer::seek(AudioMsgId::Type type, int64_t position) { QMutexLocker lock(&AudioMutex); auto current = trackForType(type); @@ -1066,20 +1066,20 @@ void Mixer::reattachTracks() { _videoTrack.reattach(AudioMsgId::Type::Video); } -void Mixer::setSongVolume(float64 volume) { +void Mixer::setSongVolume(double volume) { _volumeSong.storeRelease(qRound(volume * kVolumeRound)); } -float64 Mixer::getSongVolume() const { - return float64(_volumeSong.loadAcquire()) / kVolumeRound; +double Mixer::getSongVolume() const { + return double(_volumeSong.loadAcquire()) / kVolumeRound; } -void Mixer::setVideoVolume(float64 volume) { +void Mixer::setVideoVolume(double volume) { _volumeVideo.storeRelease(qRound(volume * kVolumeRound)); } -float64 Mixer::getVideoVolume() const { - return float64(_volumeVideo.loadAcquire()) / kVolumeRound; +double Mixer::getVideoVolume() const { + return double(_volumeVideo.loadAcquire()) / kVolumeRound; } Fader::Fader(QThread *thread) : QObject() @@ -1112,14 +1112,14 @@ void Fader::onTimer() { _suppressVolumeAll = anim::value(1., 1.); } else if (ms > _suppressAllEnd - kFadeDuration) { if (_suppressVolumeAll.to() != 1.) _suppressVolumeAll.start(1.); - _suppressVolumeAll.update(1. - ((_suppressAllEnd - ms) / float64(kFadeDuration)), anim::linear); + _suppressVolumeAll.update(1. - ((_suppressAllEnd - ms) / double(kFadeDuration)), anim::linear); } else if (ms >= _suppressAllStart + st::mediaPlayerSuppressDuration) { if (_suppressAllAnim) { _suppressVolumeAll.finish(); _suppressAllAnim = false; } } else if (ms > _suppressAllStart) { - _suppressVolumeAll.update((ms - _suppressAllStart) / float64(st::mediaPlayerSuppressDuration), anim::linear); + _suppressVolumeAll.update((ms - _suppressAllStart) / double(st::mediaPlayerSuppressDuration), anim::linear); } auto wasVolumeMultiplierAll = VolumeMultiplierAll; VolumeMultiplierAll = _suppressVolumeAll.current(); @@ -1130,7 +1130,7 @@ void Fader::onTimer() { _suppressVolumeSong.finish(); _suppressSongAnim = false; } else { - _suppressVolumeSong.update((ms - _suppressSongStart) / float64(kFadeDuration), anim::linear); + _suppressVolumeSong.update((ms - _suppressSongStart) / double(kFadeDuration), anim::linear); } } auto wasVolumeMultiplierSong = VolumeMultiplierSong; @@ -1141,7 +1141,7 @@ void Fader::onTimer() { auto hasFading = (_suppressAll || _suppressSongAnim); auto hasPlaying = false; - auto updatePlayback = [this, &hasPlaying, &hasFading](AudioMsgId::Type type, int index, float64 volumeMultiplier, bool suppressGainChanged) { + auto updatePlayback = [this, &hasPlaying, &hasFading](AudioMsgId::Type type, int index, double volumeMultiplier, bool suppressGainChanged) { auto track = mixer()->trackForType(type, index); if (IsStopped(track->state.state) || track->state.state == State::Paused || !track->isStreamCreated()) return; @@ -1174,7 +1174,7 @@ void Fader::onTimer() { } } -int32 Fader::updateOnePlayback(Mixer::Track *track, bool &hasPlaying, bool &hasFading, float64 volumeMultiplier, bool volumeChanged) { +int32_t Fader::updateOnePlayback(Mixer::Track *track, bool &hasPlaying, bool &hasFading, double volumeMultiplier, bool volumeChanged) { auto playing = false; auto fading = false; @@ -1192,7 +1192,7 @@ int32 Fader::updateOnePlayback(Mixer::Track *track, bool &hasPlaying, bool &hasF alGetSourcei(track->stream.source, AL_SOURCE_STATE, &state); if (errorHappened()) return EmitError; - int32 emitSignals = 0; + int32_t emitSignals = 0; if (state == AL_STOPPED && positionInBuffered == 0 && !internal::CheckAudioDeviceConnected()) { return emitSignals; @@ -1250,7 +1250,7 @@ int32 Fader::updateOnePlayback(Mixer::Track *track, bool &hasPlaying, bool &hasF } break; } } else { - auto newGain = TimeMs(1000) * fadingForSamplesCount / float64(kFadeDuration * track->state.frequency); + auto newGain = TimeMs(1000) * fadingForSamplesCount / double(kFadeDuration * track->state.frequency); if (track->state.state == State::Pausing || track->state.state == State::Stopping) { newGain = 1. - newGain; } @@ -1306,7 +1306,7 @@ void Fader::onUnsuppressSong() { } } -void Fader::onSuppressAll(qint64 duration) { +void Fader::onSuppressAll(int64_t duration) { _suppressAll = true; auto now = getms(); if (_suppressAllEnd < now + kFadeDuration) { @@ -1381,7 +1381,7 @@ public: FFMpegAttributesReader(const FileLocation &file, const QByteArray &data) : AbstractFFMpegLoader(file, data, base::byte_vector()) { } - bool open(qint64 &position) override { + bool open(int64_t &position) override { if (!AbstractFFMpegLoader::open(position)) { return false; } @@ -1395,7 +1395,7 @@ public: return false; } - for (int32 i = 0, l = fmtContext->nb_streams; i < l; ++i) { + for (int32_t i = 0, l = fmtContext->nb_streams; i < l; ++i) { AVStream *stream = fmtContext->streams[i]; if (stream->disposition & AV_DISPOSITION_ATTACHED_PIC) { const AVPacket &packet(stream->attached_pic); @@ -1436,7 +1436,7 @@ public: //} } - int32 format() override { + int32_t format() override { return 0; } @@ -1460,7 +1460,7 @@ public: return _coverFormat; } - ReadResult readMore(QByteArray &result, int64 &samplesAdded) override { + ReadResult readMore(QByteArray &result, int64_t &samplesAdded) override { DEBUG_LOG(("Audio Read Error: should not call this")); return ReadResult::Error; } @@ -1482,7 +1482,7 @@ namespace Player { FileLoadTask::Song PrepareForSending(const QString &fname, const QByteArray &data) { auto result = FileLoadTask::Song(); FFMpegAttributesReader reader(FileLocation(fname), data); - qint64 position = 0; + int64_t position = 0; if (reader.open(position) && reader.samplesCount() > 0) { result.duration = reader.samplesCount() / reader.samplesFrequency(); result.title = reader.title(); @@ -1500,24 +1500,24 @@ public: FFMpegWaveformCounter(const FileLocation &file, const QByteArray &data) : FFMpegLoader(file, data, base::byte_vector()) { } - bool open(qint64 &position) override { + bool open(int64_t &position) override { if (!FFMpegLoader::open(position)) { return false; } QByteArray buffer; buffer.reserve(AudioVoiceMsgBufferSize); - int64 countbytes = sampleSize * samplesCount(), processed = 0, sumbytes = 0; + int64_t countbytes = sampleSize * samplesCount(), processed = 0, sumbytes = 0; if (samplesCount() < Media::Player::kWaveformSamplesCount) { return false; } - QVector peaks; + QVector peaks; peaks.reserve(Media::Player::kWaveformSamplesCount); auto fmt = format(); - auto peak = uint16(0); - auto callback = [&peak, &sumbytes, &peaks, countbytes](uint16 sample) { + auto peak = uint16_t(0); + auto callback = [&peak, &sumbytes, &peaks, countbytes](uint16_t sample) { accumulate_max(peak, sample); sumbytes += Media::Player::kWaveformSamplesCount; if (sumbytes >= countbytes) { @@ -1529,7 +1529,7 @@ public: while (processed < countbytes) { buffer.resize(0); - int64 samples = 0; + int64_t samples = 0; auto res = readMore(buffer, samples); if (res == ReadResult::Error || res == ReadResult::EndOfFile) { break; @@ -1542,7 +1542,7 @@ public: if (fmt == AL_FORMAT_MONO8 || fmt == AL_FORMAT_STEREO8) { Media::Audio::IterateSamples(sampleBytes, callback); } else if (fmt == AL_FORMAT_MONO16 || fmt == AL_FORMAT_STEREO16) { - Media::Audio::IterateSamples(sampleBytes, callback); + Media::Audio::IterateSamples(sampleBytes, callback); } processed += sampleSize * samples; } @@ -1555,11 +1555,11 @@ public: } auto sum = std::accumulate(peaks.cbegin(), peaks.cend(), 0LL); - peak = qMax(int32(sum * 1.8 / peaks.size()), 2500); + peak = qMax(int32_t(sum * 1.8 / peaks.size()), 2500); result.resize(peaks.size()); - for (int32 i = 0, l = peaks.size(); i != l; ++i) { - result[i] = char(qMin(31U, uint32(qMin(peaks.at(i), peak)) * 31 / peak)); + for (int32_t i = 0, l = peaks.size(); i != l; ++i) { + result[i] = char(qMin(31U, uint32_t(qMin(peaks.at(i), peak)) * 31 / peak)); } return true; @@ -1579,7 +1579,7 @@ private: VoiceWaveform audioCountWaveform(const FileLocation &file, const QByteArray &data) { FFMpegWaveformCounter counter(file, data); - qint64 position = 0; + int64_t position = 0; if (counter.open(position)) { return counter.waveform(); } diff --git a/Telegram/SourceFiles/media/media_audio.h b/Telegram/SourceFiles/media/media_audio.h index 34778981b..af55d4833 100644 --- a/Telegram/SourceFiles/media/media_audio.h +++ b/Telegram/SourceFiles/media/media_audio.h @@ -59,7 +59,7 @@ class Loaders; base::Observable &Updated(); -float64 ComputeVolume(AudioMsgId::Type type); +double ComputeVolume(AudioMsgId::Type type); enum class State { Stopped = 0x01, @@ -110,8 +110,8 @@ inline bool IsActive(State state) { struct TrackState { AudioMsgId id; State state = State::Stopped; - int64 position = 0; - int64 length = 0; + int64_t position = 0; + int64_t length = 0; int frequency = kDefaultFrequency; }; @@ -121,17 +121,17 @@ class Mixer : public QObject, private base::Subscriber { public: Mixer(); - void play(const AudioMsgId &audio, int64 position = 0); - void play(const AudioMsgId &audio, std::unique_ptr videoData, int64 position = 0); + void play(const AudioMsgId &audio, int64_t position = 0); + void play(const AudioMsgId &audio, std::unique_ptr videoData, int64_t position = 0); void pause(const AudioMsgId &audio, bool fast = false); void resume(const AudioMsgId &audio, bool fast = false); - void seek(AudioMsgId::Type type, int64 position); // type == AudioMsgId::Type::Song + void seek(AudioMsgId::Type type, int64_t position); // type == AudioMsgId::Type::Song void stop(const AudioMsgId &audio); void stop(const AudioMsgId &audio, State state); // Video player audio stream interface. void feedFromVideo(VideoSoundPart &&part); - int64 getVideoCorrectedTime(const AudioMsgId &id, TimeMs frameMs, TimeMs systemMs); + int64_t getVideoCorrectedTime(const AudioMsgId &id, TimeMs frameMs, TimeMs systemMs); void stopAndClear(); @@ -149,10 +149,10 @@ public: void reattachTracks(); // Thread: Any. - void setSongVolume(float64 volume); - float64 getSongVolume() const; - void setVideoVolume(float64 volume); - float64 getVideoVolume() const; + void setSongVolume(double volume); + double getSongVolume() const; + void setVideoVolume(double volume); + double getVideoVolume() const; ~Mixer(); @@ -165,14 +165,14 @@ private slots: signals: void updated(const AudioMsgId &audio); void stoppedOnError(const AudioMsgId &audio); - void loaderOnStart(const AudioMsgId &audio, qint64 position); + void loaderOnStart(const AudioMsgId &audio, int64_t position); void loaderOnCancel(const AudioMsgId &audio); void faderOnTimer(); void suppressSong(); void unsuppressSong(); - void suppressAll(qint64 duration); + void suppressAll(int64_t duration); private: bool fadedStop(AudioMsgId::Type type, bool *fadedStart = 0); @@ -203,20 +203,20 @@ private: FileLocation file; QByteArray data; - int64 bufferedPosition = 0; - int64 bufferedLength = 0; + int64_t bufferedPosition = 0; + int64_t bufferedLength = 0; bool loading = false; bool loaded = false; - int64 fadeStartPosition = 0; + int64_t fadeStartPosition = 0; - int32 format = 0; - int32 frequency = kDefaultFrequency; + int32_t format = 0; + int32_t frequency = kDefaultFrequency; int samplesCount[kBuffersCount] = { 0 }; QByteArray bufferSamples[kBuffersCount]; struct Stream { - uint32 source = 0; - uint32 buffers[kBuffersCount] = { 0 }; + uint32_t source = 0; + uint32_t buffers[kBuffersCount] = { 0 }; }; Stream stream; std::unique_ptr videoData; @@ -279,7 +279,7 @@ public slots: void onSuppressSong(); void onUnsuppressSong(); - void onSuppressAll(qint64 duration); + void onSuppressAll(int64_t duration); void onSongVolumeChanged(); void onVideoVolumeChanged(); @@ -290,7 +290,7 @@ private: EmitPositionUpdated = 0x04, EmitNeedToPreload = 0x08, }; - int32 updateOnePlayback(Mixer::Track *track, bool &hasPlaying, bool &hasFading, float64 volumeMultiplier, bool volumeChanged); + int32_t updateOnePlayback(Mixer::Track *track, bool &hasPlaying, bool &hasFading, double volumeMultiplier, bool volumeChanged); void setStoppedState(Mixer::Track *track, State state = State::Stopped); QTimer _timer; @@ -336,11 +336,11 @@ VoiceWaveform audioCountWaveform(const FileLocation &file, const QByteArray &dat namespace Media { namespace Audio { -FORCE_INLINE uint16 ReadOneSample(uchar data) { - return qAbs((static_cast(data) - 0x80) * 0x100); +FORCE_INLINE uint16_t ReadOneSample(uchar data) { + return qAbs((static_cast(data) - 0x80) * 0x100); } -FORCE_INLINE uint16 ReadOneSample(int16 data) { +FORCE_INLINE uint16_t ReadOneSample(int16_t data) { return qAbs(data); } diff --git a/Telegram/SourceFiles/media/media_audio_capture.cpp b/Telegram/SourceFiles/media/media_audio_capture.cpp index abc170c58..fd8c3c91c 100644 --- a/Telegram/SourceFiles/media/media_audio_capture.cpp +++ b/Telegram/SourceFiles/media/media_audio_capture.cpp @@ -63,8 +63,8 @@ Instance::Instance() : _inner(new Inner(&_thread)) { CaptureInstance = this; connect(this, SIGNAL(start()), _inner, SLOT(onStart())); connect(this, SIGNAL(stop(bool)), _inner, SLOT(onStop(bool))); - connect(_inner, SIGNAL(done(QByteArray, VoiceWaveform, qint32)), this, SIGNAL(done(QByteArray, VoiceWaveform, qint32))); - connect(_inner, SIGNAL(updated(quint16, qint32)), this, SIGNAL(updated(quint16, qint32))); + connect(_inner, SIGNAL(done(QByteArray, VoiceWaveform, int32_t)), this, SIGNAL(done(QByteArray, VoiceWaveform, int32_t))); + connect(_inner, SIGNAL(updated(uint16_t, int32_t)), this, SIGNAL(updated(uint16_t, int32_t))); connect(_inner, SIGNAL(error()), this, SIGNAL(error())); connect(&_thread, SIGNAL(started()), _inner, SLOT(onInit())); connect(&_thread, SIGNAL(finished()), _inner, SLOT(deleteLater())); @@ -112,21 +112,21 @@ struct Instance::Inner::Private { uint8_t **dstSamplesData = nullptr; SwrContext *swrContext = nullptr; - int32 lastUpdate = 0; - uint16 levelMax = 0; + int32_t lastUpdate = 0; + uint16_t levelMax = 0; QByteArray data; - int32 dataPos = 0; + int32_t dataPos = 0; - int64 waveformMod = 0; - int64 waveformEach = (kCaptureFrequency / 100); - uint16 waveformPeak = 0; + int64_t waveformMod = 0; + int64_t waveformEach = (kCaptureFrequency / 100); + uint16_t waveformPeak = 0; QVector waveform; static int _read_data(void *opaque, uint8_t *buf, int buf_size) { auto l = reinterpret_cast(opaque); - int32 nbytes = qMin(l->data.size() - l->dataPos, int32(buf_size)); + int32_t nbytes = qMin(l->data.size() - l->dataPos, int32_t(buf_size)); if (nbytes <= 0) { return 0; } @@ -149,7 +149,7 @@ struct Instance::Inner::Private { static int64_t _seek_data(void *opaque, int64_t offset, int whence) { auto l = reinterpret_cast(opaque); - int32 newPos = -1; + int32_t newPos = -1; switch (whence) { case SEEK_SET: newPos = offset; break; case SEEK_CUR: newPos = l->dataPos + offset; break; @@ -357,18 +357,18 @@ void Instance::Inner::onStop(bool needResult) { d->waveformPeak = 0; d->waveform.clear(); } else { - float64 coef = 1. / fadeSamples, fadedFrom = 0; + double coef = 1. / fadeSamples, fadedFrom = 0; for (short *ptr = ((short*)_captured.data()) + capturedSamples, *end = ptr - fadeSamples; ptr != end; ++fadedFrom) { --ptr; *ptr = qRound(fadedFrom * coef * *ptr); } if (capturedSamples % d->srcSamples) { - int32 s = _captured.size(); + int32_t s = _captured.size(); _captured.resize(s + (d->srcSamples - (capturedSamples % d->srcSamples)) * sizeof(short)); memset(_captured.data() + s, 0, _captured.size() - s); } - int32 framesize = d->srcSamples * d->codecContext->channels * sizeof(short), encoded = 0; + int32_t framesize = d->srcSamples * d->codecContext->channels * sizeof(short), encoded = 0; while (_captured.size() >= encoded + framesize) { processFrame(encoded, framesize); encoded += framesize; @@ -394,16 +394,16 @@ void Instance::Inner::onStop(bool needResult) { QByteArray result = d->fullSamples ? d->data : QByteArray(); VoiceWaveform waveform; - qint32 samples = d->fullSamples; + int32_t samples = d->fullSamples; if (samples && !d->waveform.isEmpty()) { - int64 count = d->waveform.size(), sum = 0; + int64_t count = d->waveform.size(), sum = 0; if (count >= Player::kWaveformSamplesCount) { - QVector peaks; + QVector peaks; peaks.reserve(Player::kWaveformSamplesCount); - uint16 peak = 0; - for (int32 i = 0; i < count; ++i) { - uint16 sample = uint16(d->waveform.at(i)) * 256; + uint16_t peak = 0; + for (int32_t i = 0; i < count; ++i) { + uint16_t sample = uint16_t(d->waveform.at(i)) * 256; if (peak < sample) { peak = sample; } @@ -416,11 +416,11 @@ void Instance::Inner::onStop(bool needResult) { } auto sum = std::accumulate(peaks.cbegin(), peaks.cend(), 0LL); - peak = qMax(int32(sum * 1.8 / peaks.size()), 2500); + peak = qMax(int32_t(sum * 1.8 / peaks.size()), 2500); waveform.resize(peaks.size()); - for (int32 i = 0, l = peaks.size(); i != l; ++i) { - waveform[i] = char(qMin(31U, uint32(qMin(peaks.at(i), peak)) * 31 / peak)); + for (int32_t i = 0, l = peaks.size(); i != l; ++i) { + waveform[i] = char(qMin(31U, uint32_t(qMin(peaks.at(i), peak)) * 31 / peak)); } } } @@ -515,31 +515,31 @@ void Instance::Inner::onTimeout() { auto levelindex = d->fullSamples + static_cast(s / sizeof(short)); for (auto ptr = (const short*)(_captured.constData() + s), end = (const short*)(_captured.constData() + news); ptr < end; ++ptr, ++levelindex) { if (levelindex > skipSamples) { - uint16 value = qAbs(*ptr); + uint16_t value = qAbs(*ptr); if (levelindex < skipSamples + fadeSamples) { - value = qRound(value * float64(levelindex - skipSamples) / fadeSamples); + value = qRound(value * double(levelindex - skipSamples) / fadeSamples); } if (d->levelMax < value) { d->levelMax = value; } } } - qint32 samplesFull = d->fullSamples + _captured.size() / sizeof(short), samplesSinceUpdate = samplesFull - d->lastUpdate; + int32_t samplesFull = d->fullSamples + _captured.size() / sizeof(short), samplesSinceUpdate = samplesFull - d->lastUpdate; if (samplesSinceUpdate > AudioVoiceMsgUpdateView * kCaptureFrequency / 1000) { emit updated(d->levelMax, samplesFull); d->lastUpdate = samplesFull; d->levelMax = 0; } // Write frames - int32 framesize = d->srcSamples * d->codecContext->channels * sizeof(short), encoded = 0; - while (uint32(_captured.size()) >= encoded + framesize + fadeSamples * sizeof(short)) { + int32_t framesize = d->srcSamples * d->codecContext->channels * sizeof(short), encoded = 0; + while (uint32_t(_captured.size()) >= encoded + framesize + fadeSamples * sizeof(short)) { processFrame(encoded, framesize); encoded += framesize; } // Collapse the buffer if (encoded > 0) { - int32 goodSize = _captured.size() - encoded; + int32_t goodSize = _captured.size() - encoded; memmove(_captured.data(), _captured.constData() + encoded, goodSize); _captured.resize(goodSize); } @@ -548,7 +548,7 @@ void Instance::Inner::onTimeout() { } } -void Instance::Inner::processFrame(int32 offset, int32 framesize) { +void Instance::Inner::processFrame(int32_t offset, int32_t framesize) { // Prepare audio frame if (framesize % sizeof(short)) { // in the middle of a sample @@ -569,8 +569,8 @@ void Instance::Inner::processFrame(int32 offset, int32 framesize) { auto skipSamples = static_cast(kCaptureSkipDuration * kCaptureFrequency / 1000); auto fadeSamples = static_cast(kCaptureFadeInDuration * kCaptureFrequency / 1000); if (d->fullSamples < skipSamples + fadeSamples) { - int32 fadedCnt = qMin(samplesCnt, skipSamples + fadeSamples - d->fullSamples); - float64 coef = 1. / fadeSamples, fadedFrom = d->fullSamples - skipSamples; + int32_t fadedCnt = qMin(samplesCnt, skipSamples + fadeSamples - d->fullSamples); + double coef = 1. / fadeSamples, fadedFrom = d->fullSamples - skipSamples; short *ptr = srcSamplesDataChannel, *zeroEnd = ptr + qMin(samplesCnt, qMax(0, skipSamples - d->fullSamples)), *end = ptr + fadedCnt; for (; ptr != zeroEnd; ++ptr, ++fadedFrom) { *ptr = 0; @@ -582,7 +582,7 @@ void Instance::Inner::processFrame(int32 offset, int32 framesize) { d->waveform.reserve(d->waveform.size() + (samplesCnt / d->waveformEach) + 1); for (short *ptr = srcSamplesDataChannel, *end = ptr + samplesCnt; ptr != end; ++ptr) { - uint16 value = qAbs(*ptr); + uint16_t value = qAbs(*ptr); if (d->waveformPeak < value) { d->waveformPeak = value; } diff --git a/Telegram/SourceFiles/media/media_audio_capture.h b/Telegram/SourceFiles/media/media_audio_capture.h index 1c50baa41..fd74804e7 100644 --- a/Telegram/SourceFiles/media/media_audio_capture.h +++ b/Telegram/SourceFiles/media/media_audio_capture.h @@ -45,8 +45,8 @@ signals: void start(); void stop(bool needResult); - void done(QByteArray data, VoiceWaveform waveform, qint32 samples); - void updated(quint16 level, qint32 samples); + void done(QByteArray data, VoiceWaveform waveform, int32_t samples); + void updated(uint16_t level, int32_t samples); void error(); private: @@ -70,8 +70,8 @@ public: signals: void error(); - void updated(quint16 level, qint32 samples); - void done(QByteArray data, VoiceWaveform waveform, qint32 samples); + void updated(uint16_t level, int32_t samples); + void done(QByteArray data, VoiceWaveform waveform, int32_t samples); public slots: void onInit(); @@ -81,7 +81,7 @@ public slots: void onTimeout(); private: - void processFrame(int32 offset, int32 framesize); + void processFrame(int32_t offset, int32_t framesize); void writeFrame(AVFrame *frame); diff --git a/Telegram/SourceFiles/media/media_audio_ffmpeg_loader.cpp b/Telegram/SourceFiles/media/media_audio_ffmpeg_loader.cpp index 012ce56c1..bba7aaf9b 100644 --- a/Telegram/SourceFiles/media/media_audio_ffmpeg_loader.cpp +++ b/Telegram/SourceFiles/media/media_audio_ffmpeg_loader.cpp @@ -22,9 +22,9 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org constexpr AVSampleFormat AudioToFormat = AV_SAMPLE_FMT_S16; constexpr int64_t AudioToChannelLayout = AV_CH_LAYOUT_STEREO; -constexpr int32 AudioToChannels = 2; +constexpr int32_t AudioToChannels = 2; -bool AbstractFFMpegLoader::open(qint64 &position) { +bool AbstractFFMpegLoader::open(int64_t &position) { if (!AudioPlayerLoader::openFile()) { return false; } @@ -92,7 +92,7 @@ AbstractFFMpegLoader::~AbstractFFMpegLoader() { int AbstractFFMpegLoader::_read_data(void *opaque, uint8_t *buf, int buf_size) { auto l = reinterpret_cast(opaque); - auto nbytes = qMin(l->_data.size() - l->_dataPos, int32(buf_size)); + auto nbytes = qMin(l->_data.size() - l->_dataPos, int32_t(buf_size)); if (nbytes <= 0) { return 0; } @@ -105,7 +105,7 @@ int AbstractFFMpegLoader::_read_data(void *opaque, uint8_t *buf, int buf_size) { int64_t AbstractFFMpegLoader::_seek_data(void *opaque, int64_t offset, int whence) { auto l = reinterpret_cast(opaque); - int32 newPos = -1; + int32_t newPos = -1; switch (whence) { case SEEK_SET: newPos = offset; break; case SEEK_CUR: newPos = l->_dataPos + offset; break; @@ -138,7 +138,7 @@ int AbstractFFMpegLoader::_read_bytes(void *opaque, uint8_t *buf, int buf_size) int64_t AbstractFFMpegLoader::_seek_bytes(void *opaque, int64_t offset, int whence) { auto l = reinterpret_cast(opaque); - int32 newPos = -1; + int32_t newPos = -1; switch (whence) { case SEEK_SET: newPos = offset; break; case SEEK_CUR: newPos = l->_dataPos + offset; break; @@ -179,7 +179,7 @@ FFMpegLoader::FFMpegLoader(const FileLocation &file, const QByteArray &data, bas frame = av_frame_alloc(); } -bool FFMpegLoader::open(qint64 &position) { +bool FFMpegLoader::open(int64_t &position) { if (!AbstractFFMpegLoader::open(position)) { return false; } @@ -222,7 +222,7 @@ bool FFMpegLoader::open(qint64 &position) { case AV_SAMPLE_FMT_U8: case AV_SAMPLE_FMT_U8P: fmt = AL_FORMAT_MONO8; sampleSize = 1; break; case AV_SAMPLE_FMT_S16: - case AV_SAMPLE_FMT_S16P: fmt = AL_FORMAT_MONO16; sampleSize = sizeof(uint16); break; + case AV_SAMPLE_FMT_S16P: fmt = AL_FORMAT_MONO16; sampleSize = sizeof(uint16_t); break; default: sampleSize = -1; // convert needed break; @@ -231,7 +231,7 @@ bool FFMpegLoader::open(qint64 &position) { case AV_CH_LAYOUT_STEREO: switch (inputFormat) { case AV_SAMPLE_FMT_U8: fmt = AL_FORMAT_STEREO8; sampleSize = 2; break; - case AV_SAMPLE_FMT_S16: fmt = AL_FORMAT_STEREO16; sampleSize = 2 * sizeof(uint16); break; + case AV_SAMPLE_FMT_S16: fmt = AL_FORMAT_STEREO16; sampleSize = 2 * sizeof(uint16_t); break; default: sampleSize = -1; // convert needed break; @@ -281,7 +281,7 @@ bool FFMpegLoader::open(qint64 &position) { } } if (position) { - int64 ts = (position * fmtContext->streams[streamId]->time_base.den) / (_samplesFrequency * fmtContext->streams[streamId]->time_base.num); + int64_t ts = (position * fmtContext->streams[streamId]->time_base.den) / (_samplesFrequency * fmtContext->streams[streamId]->time_base.num); if (av_seek_frame(fmtContext, streamId, ts, AVSEEK_FLAG_ANY) < 0) { if (av_seek_frame(fmtContext, streamId, ts, 0) < 0) { } @@ -291,7 +291,7 @@ bool FFMpegLoader::open(qint64 &position) { return true; } -AudioPlayerLoader::ReadResult FFMpegLoader::readMore(QByteArray &result, int64 &samplesAdded) { +AudioPlayerLoader::ReadResult FFMpegLoader::readMore(QByteArray &result, int64_t &samplesAdded) { int res; av_frame_unref(frame); @@ -337,7 +337,7 @@ AudioPlayerLoader::ReadResult FFMpegLoader::readMore(QByteArray &result, int64 & return ReadResult::Ok; } -AudioPlayerLoader::ReadResult FFMpegLoader::readFromReadyFrame(QByteArray &result, int64 &samplesAdded) { +AudioPlayerLoader::ReadResult FFMpegLoader::readFromReadyFrame(QByteArray &result, int64_t &samplesAdded) { int res = 0; if (dstSamplesData) { // convert needed @@ -356,7 +356,7 @@ AudioPlayerLoader::ReadResult FFMpegLoader::readFromReadyFrame(QByteArray &resul LOG(("Audio Error: Unable to swr_convert for file '%1', data size '%2', error %3, %4").arg(_file.name()).arg(_data.size()).arg(res).arg(av_make_error_string(err, sizeof(err), res))); return ReadResult::Error; } - int32 resultLen = av_samples_get_buffer_size(0, AudioToChannels, res, AudioToFormat, 1); + int32_t resultLen = av_samples_get_buffer_size(0, AudioToChannels, res, AudioToFormat, 1); result.append((const char*)dstSamplesData[0], resultLen); samplesAdded += resultLen / sampleSize; } else { diff --git a/Telegram/SourceFiles/media/media_audio_ffmpeg_loader.h b/Telegram/SourceFiles/media/media_audio_ffmpeg_loader.h index a66ff539a..f9e723636 100644 --- a/Telegram/SourceFiles/media/media_audio_ffmpeg_loader.h +++ b/Telegram/SourceFiles/media/media_audio_ffmpeg_loader.h @@ -37,27 +37,27 @@ public: AbstractFFMpegLoader(const FileLocation &file, const QByteArray &data, base::byte_vector &&bytes) : AudioPlayerLoader(file, data, std::move(bytes)) { } - bool open(qint64 &position) override; + bool open(int64_t &position) override; - int64 samplesCount() override { + int64_t samplesCount() override { return _samplesCount; } - int32 samplesFrequency() override { + int32_t samplesFrequency() override { return _samplesFrequency; } ~AbstractFFMpegLoader(); protected: - int32 _samplesFrequency = Media::Player::kDefaultFrequency; - int64 _samplesCount = 0; + int32_t _samplesFrequency = Media::Player::kDefaultFrequency; + int64_t _samplesCount = 0; uchar *ioBuffer = nullptr; AVIOContext *ioContext = nullptr; AVFormatContext *fmtContext = nullptr; AVCodec *codec = nullptr; - int32 streamId = 0; + int32_t streamId = 0; bool _opened = false; @@ -75,26 +75,26 @@ class FFMpegLoader : public AbstractFFMpegLoader { public: FFMpegLoader(const FileLocation &file, const QByteArray &data, base::byte_vector &&bytes); - bool open(qint64 &position) override; + bool open(int64_t &position) override; - int32 format() override { + int32_t format() override { return fmt; } - ReadResult readMore(QByteArray &result, int64 &samplesAdded) override; + ReadResult readMore(QByteArray &result, int64_t &samplesAdded) override; ~FFMpegLoader(); protected: - int32 sampleSize = 2 * sizeof(uint16); + int32_t sampleSize = 2 * sizeof(uint16_t); private: - ReadResult readFromReadyFrame(QByteArray &result, int64 &samplesAdded); + ReadResult readFromReadyFrame(QByteArray &result, int64_t &samplesAdded); - int32 fmt = AL_FORMAT_STEREO16; - int32 srcRate = Media::Player::kDefaultFrequency; - int32 dstRate = Media::Player::kDefaultFrequency; - int32 maxResampleSamples = 1024; + int32_t fmt = AL_FORMAT_STEREO16; + int32_t srcRate = Media::Player::kDefaultFrequency; + int32_t dstRate = Media::Player::kDefaultFrequency; + int32_t maxResampleSamples = 1024; uint8_t **dstSamplesData = nullptr; AVCodecContext *codecContext = nullptr; diff --git a/Telegram/SourceFiles/media/media_audio_loader.cpp b/Telegram/SourceFiles/media/media_audio_loader.cpp index c63435f8c..dc06ffca9 100644 --- a/Telegram/SourceFiles/media/media_audio_loader.cpp +++ b/Telegram/SourceFiles/media/media_audio_loader.cpp @@ -37,7 +37,7 @@ bool AudioPlayerLoader::check(const FileLocation &file, const QByteArray &data) return this->_file == file && this->_data.size() == data.size(); } -void AudioPlayerLoader::saveDecodedSamples(QByteArray *samples, int64 *samplesCount) { +void AudioPlayerLoader::saveDecodedSamples(QByteArray *samples, int64_t *samplesCount) { Assert(_savedSamplesCount == 0); Assert(_savedSamples.isEmpty()); Assert(!_holdsSavedSamples); @@ -46,7 +46,7 @@ void AudioPlayerLoader::saveDecodedSamples(QByteArray *samples, int64 *samplesCo _holdsSavedSamples = true; } -void AudioPlayerLoader::takeSavedDecodedSamples(QByteArray *samples, int64 *samplesCount) { +void AudioPlayerLoader::takeSavedDecodedSamples(QByteArray *samples, int64_t *samplesCount) { Assert(*samplesCount == 0); Assert(samples->isEmpty()); Assert(_holdsSavedSamples); diff --git a/Telegram/SourceFiles/media/media_audio_loader.h b/Telegram/SourceFiles/media/media_audio_loader.h index 5835b9447..96e731999 100644 --- a/Telegram/SourceFiles/media/media_audio_loader.h +++ b/Telegram/SourceFiles/media/media_audio_loader.h @@ -31,10 +31,10 @@ public: virtual bool check(const FileLocation &file, const QByteArray &data); - virtual bool open(qint64 &position) = 0; - virtual int64 samplesCount() = 0; - virtual int32 samplesFrequency() = 0; - virtual int32 format() = 0; + virtual bool open(int64_t &position) = 0; + virtual int64_t samplesCount() = 0; + virtual int32_t samplesFrequency() = 0; + virtual int32_t format() = 0; enum class ReadResult { Error, @@ -43,13 +43,13 @@ public: Wait, EndOfFile, }; - virtual ReadResult readMore(QByteArray &samples, int64 &samplesCount) = 0; + virtual ReadResult readMore(QByteArray &samples, int64_t &samplesCount) = 0; virtual void enqueuePackets(QQueue &packets) { Unexpected("enqueuePackets() call on not ChildFFMpegLoader."); } - void saveDecodedSamples(QByteArray *samples, int64 *samplesCount); - void takeSavedDecodedSamples(QByteArray *samples, int64 *samplesCount); + void saveDecodedSamples(QByteArray *samples, int64_t *samplesCount); + void takeSavedDecodedSamples(QByteArray *samples, int64_t *samplesCount); bool holdsSavedDecodedSamples() const; protected: @@ -65,7 +65,7 @@ protected: private: QByteArray _savedSamples; - int64 _savedSamplesCount = 0; + int64_t _savedSamplesCount = 0; bool _holdsSavedSamples = false; }; diff --git a/Telegram/SourceFiles/media/media_audio_loaders.cpp b/Telegram/SourceFiles/media/media_audio_loaders.cpp index ccd6e7258..18a764f7d 100644 --- a/Telegram/SourceFiles/media/media_audio_loaders.cpp +++ b/Telegram/SourceFiles/media/media_audio_loaders.cpp @@ -98,7 +98,7 @@ void Loaders::clearFromVideoQueue() { void Loaders::onInit() { } -void Loaders::onStart(const AudioMsgId &audio, qint64 position) { +void Loaders::onStart(const AudioMsgId &audio, int64_t position) { auto type = audio.type(); clear(type); { @@ -136,7 +136,7 @@ void Loaders::onLoad(const AudioMsgId &audio) { loadData(audio, 0); } -void Loaders::loadData(AudioMsgId audio, qint64 position) { +void Loaders::loadData(AudioMsgId audio, int64_t position) { auto err = SetupNoErrorStarted; auto type = audio.type(); auto l = setupLoader(audio, err, position); @@ -153,7 +153,7 @@ void Loaders::loadData(AudioMsgId audio, qint64 position) { auto errAtStart = started; QByteArray samples; - int64 samplesCount = 0; + int64_t samplesCount = 0; if (l->holdsSavedDecodedSamples()) { l->takeSavedDecodedSamples(&samples, &samplesCount); } @@ -291,7 +291,7 @@ void Loaders::loadData(AudioMsgId audio, qint64 position) { } } -AudioPlayerLoader *Loaders::setupLoader(const AudioMsgId &audio, SetupError &err, qint64 &position) { +AudioPlayerLoader *Loaders::setupLoader(const AudioMsgId &audio, SetupError &err, int64_t &position) { err = SetupErrorAtStart; QMutexLocker lock(internal::audioPlayerMutex()); if (!mixer()) return nullptr; diff --git a/Telegram/SourceFiles/media/media_audio_loaders.h b/Telegram/SourceFiles/media/media_audio_loaders.h index e3d7dfc71..652347734 100644 --- a/Telegram/SourceFiles/media/media_audio_loaders.h +++ b/Telegram/SourceFiles/media/media_audio_loaders.h @@ -45,7 +45,7 @@ signals: public slots: void onInit(); - void onStart(const AudioMsgId &audio, qint64 position); + void onStart(const AudioMsgId &audio, int64_t position); void onLoad(const AudioMsgId &audio); void onCancel(const AudioMsgId &audio); @@ -72,8 +72,8 @@ private: SetupErrorLoadedFull = 2, SetupNoErrorStarted = 3, }; - void loadData(AudioMsgId audio, qint64 position); - AudioPlayerLoader *setupLoader(const AudioMsgId &audio, SetupError &err, qint64 &position); + void loadData(AudioMsgId audio, int64_t position); + AudioPlayerLoader *setupLoader(const AudioMsgId &audio, SetupError &err, int64_t &position); Mixer::Track *checkLoader(AudioMsgId::Type type); }; diff --git a/Telegram/SourceFiles/media/media_audio_track.cpp b/Telegram/SourceFiles/media/media_audio_track.cpp index 51efe4a77..e11a2e871 100644 --- a/Telegram/SourceFiles/media/media_audio_track.cpp +++ b/Telegram/SourceFiles/media/media_audio_track.cpp @@ -65,7 +65,7 @@ void Track::samplePeakEach(TimeMs peakDuration) { void Track::fillFromData(base::byte_vector &&data) { FFMpegLoader loader(FileLocation(), QByteArray(), std::move(data)); - auto position = qint64(0); + auto position = int64_t(0); if (!loader.open(position)) { _failed = true; return; @@ -74,12 +74,12 @@ void Track::fillFromData(base::byte_vector &&data) { _peakEachPosition = _peakDurationMs ? ((loader.samplesFrequency() * _peakDurationMs) / 1000) : 0; auto peaksCount = _peakEachPosition ? (loader.samplesCount() / _peakEachPosition) : 0; _peaks.reserve(peaksCount); - auto peakValue = uint16(0); + auto peakValue = uint16_t(0); auto peakSamples = 0; auto peakEachSample = (format == AL_FORMAT_STEREO8 || format == AL_FORMAT_STEREO16) ? (_peakEachPosition * 2) : _peakEachPosition; _peakValueMin = 0x7FFF; _peakValueMax = 0; - auto peakCallback = [this, &peakValue, &peakSamples, peakEachSample](uint16 sample) { + auto peakCallback = [this, &peakValue, &peakSamples, peakEachSample](uint16_t sample) { accumulate_max(peakValue, sample); if (++peakSamples >= peakEachSample) { peakSamples -= peakEachSample; @@ -91,7 +91,7 @@ void Track::fillFromData(base::byte_vector &&data) { }; do { auto buffer = QByteArray(); - auto samplesAdded = int64(0); + auto samplesAdded = int64_t(0); auto result = loader.readMore(buffer, samplesAdded); if (samplesAdded > 0) { auto sampleBytes = gsl::as_bytes(gsl::make_span(buffer)); @@ -101,7 +101,7 @@ void Track::fillFromData(base::byte_vector &&data) { if (format == AL_FORMAT_MONO8 || format == AL_FORMAT_STEREO8) { Media::Audio::IterateSamples(sampleBytes, peakCallback); } else if (format == AL_FORMAT_MONO16 || format == AL_FORMAT_STEREO16) { - Media::Audio::IterateSamples(sampleBytes, peakCallback); + Media::Audio::IterateSamples(sampleBytes, peakCallback); } } } @@ -216,7 +216,7 @@ void Track::updateState() { } } -float64 Track::getPeakValue(TimeMs when) const { +double Track::getPeakValue(TimeMs when) const { if (!isActive() || !_samplesCount || _peaks.empty() || _peakValueMin == _peakValueMax) { return 0.; } @@ -226,7 +226,7 @@ float64 Track::getPeakValue(TimeMs when) const { } sampleIndex = sampleIndex % _samplesCount; auto peakIndex = (sampleIndex / _peakEachPosition) % _peaks.size(); - return (_peaks[peakIndex] - _peakValueMin) / float64(_peakValueMax - _peakValueMin); + return (_peaks[peakIndex] - _peakValueMin) / double(_peakValueMax - _peakValueMin); } void Track::detachFromDevice() { diff --git a/Telegram/SourceFiles/media/media_audio_track.h b/Telegram/SourceFiles/media/media_audio_track.h index b14a12c40..715c29735 100644 --- a/Telegram/SourceFiles/media/media_audio_track.h +++ b/Telegram/SourceFiles/media/media_audio_track.h @@ -54,10 +54,10 @@ public: return _failed; } - int64 getLengthMs() const { + int64_t getLengthMs() const { return _lengthMs; } - float64 getPeakValue(TimeMs when) const; + double getPeakValue(TimeMs when) const; void detachFromDevice(); void reattachToDevice(); @@ -75,25 +75,25 @@ private: bool _failed = false; bool _active = false; bool _looping = false; - float64 _volume = 1.; + double _volume = 1.; - int64 _samplesCount = 0; - int32 _sampleRate = 0; + int64_t _samplesCount = 0; + int32_t _sampleRate = 0; base::byte_vector _samples; TimeMs _peakDurationMs = 0; int _peakEachPosition = 0; - std::vector _peaks; - uint16 _peakValueMin = 0; - uint16 _peakValueMax = 0; + std::vector _peaks; + uint16_t _peakValueMin = 0; + uint16_t _peakValueMax = 0; TimeMs _lengthMs = 0; TimeMs _stateUpdatedAt = 0; - int32 _alFormat = 0; - int64 _alPosition = 0; - uint32 _alSource = 0; - uint32 _alBuffer = 0; + int32_t _alFormat = 0; + int64_t _alPosition = 0; + uint32_t _alSource = 0; + uint32_t _alBuffer = 0; }; diff --git a/Telegram/SourceFiles/media/media_child_ffmpeg_loader.cpp b/Telegram/SourceFiles/media/media_child_ffmpeg_loader.cpp index bb7e57e66..2b4a368b9 100644 --- a/Telegram/SourceFiles/media/media_child_ffmpeg_loader.cpp +++ b/Telegram/SourceFiles/media/media_child_ffmpeg_loader.cpp @@ -22,7 +22,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org constexpr AVSampleFormat AudioToFormat = AV_SAMPLE_FMT_S16; constexpr int64_t AudioToChannelLayout = AV_CH_LAYOUT_STEREO; -constexpr int32 AudioToChannels = 2; +constexpr int32_t AudioToChannels = 2; VideoSoundData::~VideoSoundData() { if (context) { @@ -37,7 +37,7 @@ ChildFFMpegLoader::ChildFFMpegLoader(std::unique_ptr &&data) : A _frame = av_frame_alloc(); } -bool ChildFFMpegLoader::open(qint64 &position) { +bool ChildFFMpegLoader::open(int64_t &position) { int res = 0; char err[AV_ERROR_MAX_STRING_SIZE] = { 0 }; @@ -57,7 +57,7 @@ bool ChildFFMpegLoader::open(qint64 &position) { case AV_SAMPLE_FMT_U8: case AV_SAMPLE_FMT_U8P: _format = AL_FORMAT_MONO8; _sampleSize = 1; break; case AV_SAMPLE_FMT_S16: - case AV_SAMPLE_FMT_S16P: _format = AL_FORMAT_MONO16; _sampleSize = sizeof(uint16); break; + case AV_SAMPLE_FMT_S16P: _format = AL_FORMAT_MONO16; _sampleSize = sizeof(uint16_t); break; default: _sampleSize = -1; // convert needed break; @@ -66,7 +66,7 @@ bool ChildFFMpegLoader::open(qint64 &position) { case AV_CH_LAYOUT_STEREO: switch (_inputFormat) { case AV_SAMPLE_FMT_U8: _format = AL_FORMAT_STEREO8; _sampleSize = 2; break; - case AV_SAMPLE_FMT_S16: _format = AL_FORMAT_STEREO16; _sampleSize = 2 * sizeof(uint16); break; + case AV_SAMPLE_FMT_S16: _format = AL_FORMAT_STEREO16; _sampleSize = 2 * sizeof(uint16_t); break; default: _sampleSize = -1; // convert needed break; @@ -119,7 +119,7 @@ bool ChildFFMpegLoader::open(qint64 &position) { return true; } -AudioPlayerLoader::ReadResult ChildFFMpegLoader::readMore(QByteArray &result, int64 &samplesAdded) { +AudioPlayerLoader::ReadResult ChildFFMpegLoader::readMore(QByteArray &result, int64_t &samplesAdded) { int res; av_frame_unref(_frame); @@ -166,7 +166,7 @@ AudioPlayerLoader::ReadResult ChildFFMpegLoader::readMore(QByteArray &result, in return ReadResult::Ok; } -AudioPlayerLoader::ReadResult ChildFFMpegLoader::readFromReadyFrame(QByteArray &result, int64 &samplesAdded) { +AudioPlayerLoader::ReadResult ChildFFMpegLoader::readFromReadyFrame(QByteArray &result, int64_t &samplesAdded) { int res = 0; if (_dstSamplesData) { // convert needed @@ -185,7 +185,7 @@ AudioPlayerLoader::ReadResult ChildFFMpegLoader::readFromReadyFrame(QByteArray & LOG(("Audio Error: Unable to swr_convert for file '%1', data size '%2', error %3, %4").arg(_file.name()).arg(_data.size()).arg(res).arg(av_make_error_string(err, sizeof(err), res))); return ReadResult::Error; } - int32 resultLen = av_samples_get_buffer_size(0, AudioToChannels, res, AudioToFormat, 1); + int32_t resultLen = av_samples_get_buffer_size(0, AudioToChannels, res, AudioToFormat, 1); result.append((const char*)_dstSamplesData[0], resultLen); samplesAdded += resultLen / _sampleSize; } else { diff --git a/Telegram/SourceFiles/media/media_child_ffmpeg_loader.h b/Telegram/SourceFiles/media/media_child_ffmpeg_loader.h index fdeea40b8..2bb4e0bb3 100644 --- a/Telegram/SourceFiles/media/media_child_ffmpeg_loader.h +++ b/Telegram/SourceFiles/media/media_child_ffmpeg_loader.h @@ -34,15 +34,15 @@ extern "C" { struct VideoSoundData { AVCodecContext *context = nullptr; - int32 frequency = Media::Player::kDefaultFrequency; - int64 length = 0; + int32_t frequency = Media::Player::kDefaultFrequency; + int64_t length = 0; ~VideoSoundData(); }; struct VideoSoundPart { AVPacket *packet = nullptr; AudioMsgId audio; - uint32 playId = 0; + uint32_t playId = 0; }; namespace FFMpeg { @@ -85,25 +85,25 @@ class ChildFFMpegLoader : public AudioPlayerLoader { public: ChildFFMpegLoader(std::unique_ptr &&data); - bool open(qint64 &position) override; + bool open(int64_t &position) override; bool check(const FileLocation &file, const QByteArray &data) override { return true; } - int32 format() override { + int32_t format() override { return _format; } - int64 samplesCount() override { + int64_t samplesCount() override { return _parentData->length; } - int32 samplesFrequency() override { + int32_t samplesFrequency() override { return _parentData->frequency; } - ReadResult readMore(QByteArray &result, int64 &samplesAdded) override; + ReadResult readMore(QByteArray &result, int64_t &samplesAdded) override; void enqueuePackets(QQueue &packets) override; bool eofReached() const { @@ -113,15 +113,15 @@ public: ~ChildFFMpegLoader(); private: - ReadResult readFromReadyFrame(QByteArray &result, int64 &samplesAdded); + ReadResult readFromReadyFrame(QByteArray &result, int64_t &samplesAdded); bool _eofReached = false; - int32 _sampleSize = 2 * sizeof(uint16); - int32 _format = AL_FORMAT_STEREO16; - int32 _srcRate = Media::Player::kDefaultFrequency; - int32 _dstRate = Media::Player::kDefaultFrequency; - int32 _maxResampleSamples = 1024; + int32_t _sampleSize = 2 * sizeof(uint16_t); + int32_t _format = AL_FORMAT_STEREO16; + int32_t _srcRate = Media::Player::kDefaultFrequency; + int32_t _dstRate = Media::Player::kDefaultFrequency; + int32_t _maxResampleSamples = 1024; uint8_t **_dstSamplesData = nullptr; std::unique_ptr _parentData; diff --git a/Telegram/SourceFiles/media/media_clip_ffmpeg.cpp b/Telegram/SourceFiles/media/media_clip_ffmpeg.cpp index ebd47d3db..b776cfd38 100644 --- a/Telegram/SourceFiles/media/media_clip_ffmpeg.cpp +++ b/Telegram/SourceFiles/media/media_clip_ffmpeg.cpp @@ -149,12 +149,12 @@ ReaderImplementation::ReadResult FFMpegReaderImplementation::readNextFrame() { } void FFMpegReaderImplementation::processReadFrame() { - int64 duration = _frame->pkt_duration; - int64 framePts = _frame->pts; + int64_t duration = _frame->pkt_duration; + int64_t framePts = _frame->pts; TimeMs frameMs = (framePts * 1000LL * _fmtContext->streams[_streamId]->time_base.num) / _fmtContext->streams[_streamId]->time_base.den; _currentFrameDelay = _nextFrameDelay; if (_frameMs + _currentFrameDelay < frameMs) { - _currentFrameDelay = int32(frameMs - _frameMs); + _currentFrameDelay = int32_t(frameMs - _frameMs); } else if (frameMs < _frameMs + _currentFrameDelay) { frameMs = _frameMs + _currentFrameDelay; } @@ -240,9 +240,9 @@ bool FFMpegReaderImplementation::renderFrame(QImage &to, bool &hasAlpha, const Q } hasAlpha = (_frame->format == AV_PIX_FMT_BGRA || (_frame->format == -1 && _codecContext->pix_fmt == AV_PIX_FMT_BGRA)); if (_frame->width == toSize.width() && _frame->height == toSize.height() && hasAlpha) { - int32 sbpl = _frame->linesize[0], dbpl = to.bytesPerLine(), bpl = qMin(sbpl, dbpl); + int32_t sbpl = _frame->linesize[0], dbpl = to.bytesPerLine(), bpl = qMin(sbpl, dbpl); uchar *s = _frame->data[0], *d = to.bits(); - for (int32 i = 0, l = _frame->height; i < l; ++i) { + for (int32_t i = 0, l = _frame->height; i < l; ++i) { memcpy(d + i * dbpl, s + i * sbpl, bpl); } } else { @@ -537,7 +537,7 @@ void FFMpegReaderImplementation::processPacket(AVPacket *packet) { } TimeMs FFMpegReaderImplementation::countPacketMs(AVPacket *packet) const { - int64 packetPts = (packet->pts == AV_NOPTS_VALUE) ? packet->dts : packet->pts; + int64_t packetPts = (packet->pts == AV_NOPTS_VALUE) ? packet->dts : packet->pts; TimeMs packetMs = (packetPts * 1000LL * _fmtContext->streams[packet->stream_index]->time_base.num) / _fmtContext->streams[packet->stream_index]->time_base.den; return packetMs; } diff --git a/Telegram/SourceFiles/media/media_clip_implementation.h b/Telegram/SourceFiles/media/media_clip_implementation.h index 43e6d5fc9..ea6508acb 100644 --- a/Telegram/SourceFiles/media/media_clip_implementation.h +++ b/Telegram/SourceFiles/media/media_clip_implementation.h @@ -60,7 +60,7 @@ public: virtual ~ReaderImplementation() { } - int64 dataSize() const { + int64_t dataSize() const { return _dataSize; } @@ -70,7 +70,7 @@ protected: QFile _file; QBuffer _buffer; QIODevice *_device = nullptr; - int64 _dataSize = 0; + int64_t _dataSize = 0; void initDevice(); diff --git a/Telegram/SourceFiles/media/media_clip_qtgif.cpp b/Telegram/SourceFiles/media/media_clip_qtgif.cpp index 890d55d36..eef56034e 100644 --- a/Telegram/SourceFiles/media/media_clip_qtgif.cpp +++ b/Telegram/SourceFiles/media/media_clip_qtgif.cpp @@ -73,7 +73,7 @@ ReaderImplementation::ReadResult QtGifReaderImplementation::readNextFrame() { bool QtGifReaderImplementation::renderFrame(QImage &to, bool &hasAlpha, const QSize &size) { Assert(!_frame.isNull()); if (size.isEmpty() || size == _frame.size()) { - int32 w = _frame.width(), h = _frame.height(); + int32_t w = _frame.width(), h = _frame.height(); if (to.width() == w && to.height() == h && to.format() == _frame.format()) { if (to.byteCount() != _frame.byteCount()) { int bpl = qMin(to.bytesPerLine(), _frame.bytesPerLine()); diff --git a/Telegram/SourceFiles/media/media_clip_reader.cpp b/Telegram/SourceFiles/media/media_clip_reader.cpp index 7c38913be..d80a4454e 100644 --- a/Telegram/SourceFiles/media/media_clip_reader.cpp +++ b/Telegram/SourceFiles/media/media_clip_reader.cpp @@ -93,17 +93,17 @@ QPixmap PrepareFrame(const FrameRequest &request, const QImage &original, bool h } // namespace -Reader::Reader(const QString &filepath, Callback &&callback, Mode mode, int64 seekMs) +Reader::Reader(const QString &filepath, Callback &&callback, Mode mode, int64_t seekMs) : _callback(std::move(callback)) , _mode(mode) , _seekPositionMs(seekMs) { init(FileLocation(filepath), QByteArray()); } -Reader::Reader(not_null document, FullMsgId msgId, Callback &&callback, Mode mode, int64 seekMs) +Reader::Reader(not_null document, FullMsgId msgId, Callback &&callback, Mode mode, int64_t seekMs) : _callback(std::move(callback)) , _mode(mode) -, _audioMsgId(document, msgId, (mode == Mode::Video) ? rand_value() : 0) +, _audioMsgId(document, msgId, (mode == Mode::Video) ? rand_value() : 0) , _seekPositionMs(seekMs) { init(document->location(), document->data()); } @@ -115,10 +115,10 @@ void Reader::init(const FileLocation &location, const QByteArray &data) { managers.push_back(new Manager(threads.back())); threads.back()->start(); } else { - _threadIndex = int32(rand_value() % threads.size()); - int32 loadLevel = 0x7FFFFFFF; - for (int32 i = 0, l = threads.size(); i < l; ++i) { - int32 level = managers.at(i)->loadLevel(); + _threadIndex = int32_t(rand_value() % threads.size()); + int32_t loadLevel = 0x7FFFFFFF; + for (int32_t i = 0, l = threads.size(); i < l; ++i) { + int32_t level = managers.at(i)->loadLevel(); if (level < loadLevel) { _threadIndex = i; loadLevel = level; @@ -128,7 +128,7 @@ void Reader::init(const FileLocation &location, const QByteArray &data) { managers.at(_threadIndex)->append(this, location, data); } -Reader::Frame *Reader::frameToShow(int32 *index) const { // 0 means not ready +Reader::Frame *Reader::frameToShow(int32_t *index) const { // 0 means not ready int step = _step.loadAcquire(), i; if (step == WaitingForDimensionsStep) { if (index) *index = 0; @@ -144,8 +144,8 @@ Reader::Frame *Reader::frameToShow(int32 *index) const { // 0 means not ready return _frames + i; } -Reader::Frame *Reader::frameToWrite(int32 *index) const { // 0 means not ready - int32 step = _step.loadAcquire(), i; +Reader::Frame *Reader::frameToWrite(int32_t *index) const { // 0 means not ready + int32_t step = _step.loadAcquire(), i; if (step == WaitingForDimensionsStep) { i = 0; } else if (step == WaitingForRequestStep) { @@ -160,8 +160,8 @@ Reader::Frame *Reader::frameToWrite(int32 *index) const { // 0 means not ready return _frames + i; } -Reader::Frame *Reader::frameToWriteNext(bool checkNotWriting, int32 *index) const { - int32 step = _step.loadAcquire(), i; +Reader::Frame *Reader::frameToWriteNext(bool checkNotWriting, int32_t *index) const { + int32_t step = _step.loadAcquire(), i; if (step == WaitingForDimensionsStep || step == WaitingForRequestStep || (checkNotWriting && (step % 2))) { if (index) *index = 0; return nullptr; @@ -172,7 +172,7 @@ Reader::Frame *Reader::frameToWriteNext(bool checkNotWriting, int32 *index) cons } void Reader::moveToNextShow() const { - int32 step = _step.loadAcquire(); + int32_t step = _step.loadAcquire(); if (step == WaitingForDimensionsStep) { } else if (step == WaitingForRequestStep) { _step.storeRelease(WaitingForFirstFrameStep); @@ -183,7 +183,7 @@ void Reader::moveToNextShow() const { } void Reader::moveToNextWrite() const { - int32 step = _step.loadAcquire(); + int32_t step = _step.loadAcquire(); if (step == WaitingForDimensionsStep) { _step.storeRelease(WaitingForRequestStep); } else if (step == WaitingForRequestStep) { @@ -197,14 +197,14 @@ void Reader::moveToNextWrite() const { } } -void Reader::callback(Reader *reader, int32 threadIndex, Notification notification) { +void Reader::callback(Reader *reader, int32_t threadIndex, Notification notification) { // check if reader is not deleted already if (managers.size() > threadIndex && managers.at(threadIndex)->carries(reader) && reader->_callback) { reader->_callback(notification); } } -void Reader::start(int32 framew, int32 frameh, int32 outerw, int32 outerh, ImageRoundRadius radius, ImageRoundCorners corners) { +void Reader::start(int32_t framew, int32_t frameh, int32_t outerw, int32_t outerh, ImageRoundRadius radius, ImageRoundCorners corners) { if (managers.size() <= _threadIndex) error(); if (_state == State::Error) return; @@ -224,7 +224,7 @@ void Reader::start(int32 framew, int32 frameh, int32 outerw, int32 outerh, Image } } -QPixmap Reader::current(int32 framew, int32 frameh, int32 outerw, int32 outerh, ImageRoundRadius radius, ImageRoundCorners corners, TimeMs ms) { +QPixmap Reader::current(int32_t framew, int32_t frameh, int32_t outerw, int32_t outerh, ImageRoundRadius radius, ImageRoundCorners corners, TimeMs ms) { Expects(outerw > 0); Expects(outerh > 0); @@ -327,11 +327,11 @@ bool Reader::videoPaused() const { return _videoPauseRequest.loadAcquire() != 0; } -int32 Reader::width() const { +int32_t Reader::width() const { return _width; } -int32 Reader::height() const { +int32_t Reader::height() const { return _height; } @@ -697,7 +697,7 @@ bool Manager::handleProcessResult(ReaderPrivate *reader, ProcessResult result, T } // See if we need to pause GIF because it is not displayed right now. if (!reader->_autoPausedGif && reader->_mode == Reader::Mode::Gif && result == ProcessResult::Repaint) { - int32 ishowing, iprevious; + int32_t ishowing, iprevious; auto showing = it.key()->frameToShow(&ishowing), previous = it.key()->frameToWriteNext(false, &iprevious); Assert(previous != nullptr && showing != nullptr && ishowing >= 0 && iprevious >= 0); if (reader->_frames[ishowing].when > 0 && showing->displayed.loadAcquire() <= 0) { // current frame was not shown @@ -748,7 +748,7 @@ Manager::ResultHandleState Manager::handleResult(ReaderPrivate *reader, ProcessR QMutexLocker lock(&_readerPointersMutex); auto it = constUnsafeFindReaderPointer(reader); if (it != _readerPointers.cend()) { - int32 index = 0; + int32_t index = 0; Reader *r = it.key(); Reader::Frame *frame = it.key()->frameToWrite(&index); if (frame) { @@ -910,7 +910,7 @@ FileLoadTask::Video PrepareForSending(const QString &fname, const QByteArray &da void Finish() { if (!threads.isEmpty()) { - for (int32 i = 0, l = threads.size(); i < l; ++i) { + for (int32_t i = 0, l = threads.size(); i < l; ++i) { threads.at(i)->quit(); DEBUG_LOG(("Waiting for clipThread to finish: %1").arg(i)); threads.at(i)->wait(); diff --git a/Telegram/SourceFiles/media/media_clip_reader.h b/Telegram/SourceFiles/media/media_clip_reader.h index dae972eae..511998f78 100644 --- a/Telegram/SourceFiles/media/media_clip_reader.h +++ b/Telegram/SourceFiles/media/media_clip_reader.h @@ -169,7 +169,7 @@ private: QAtomicInt _autoPausedGif = 0; QAtomicInt _videoPauseRequest = 0; - int32 _threadIndex; + int32_t _threadIndex; bool _autoplay = false; @@ -200,7 +200,7 @@ class Manager : public QObject { public: Manager(QThread *thread); - int32 loadLevel() const { + int32_t loadLevel() const { return _loadLevel.load(); } void append(Reader *reader, const FileLocation &location, const QByteArray &data); @@ -213,7 +213,7 @@ public: signals: void processDelayed(); - void callback(Media::Clip::Reader *reader, qint32 threadIndex, qint32 notification); + void callback(Media::Clip::Reader *reader, int32_t threadIndex, int32_t notification); public slots: void process(); diff --git a/Telegram/SourceFiles/media/player/media_player_button.cpp b/Telegram/SourceFiles/media/player/media_player_button.cpp index fb944e072..d3d8dd41d 100644 --- a/Telegram/SourceFiles/media/player/media_player_button.cpp +++ b/Telegram/SourceFiles/media/player/media_player_button.cpp @@ -105,7 +105,7 @@ void PlayButtonLayout::paintPlay(Painter &p, const QBrush &brush) { p.fillPath(pathPlay, brush); } -void PlayButtonLayout::paintPlayToPause(Painter &p, const QBrush &brush, float64 progress) { +void PlayButtonLayout::paintPlayToPause(Painter &p, const QBrush &brush, double progress) { auto playLeft = 0. + _st.playPosition.x(); auto playTop = 0. + _st.playPosition.y(); auto playWidth = _st.playOuter.width() - 2 * playLeft; @@ -149,7 +149,7 @@ void PlayButtonLayout::paintPlayToPause(Painter &p, const QBrush &brush, float64 p.fillPath(anim::interpolate(pathRightPlay, pathRightPause, progress), brush); } -void PlayButtonLayout::paintPlayToCancel(Painter &p, const QBrush &brush, float64 progress) { +void PlayButtonLayout::paintPlayToCancel(Painter &p, const QBrush &brush, double progress) { static const auto sqrt2 = sqrt(2.); auto playLeft = 0. + _st.playPosition.x(); @@ -197,7 +197,7 @@ void PlayButtonLayout::paintPlayToCancel(Painter &p, const QBrush &brush, float6 p.fillPath(anim::interpolate(pathPlay, pathCancel, progress), brush); } -void PlayButtonLayout::paintPauseToCancel(Painter &p, const QBrush &brush, float64 progress) { +void PlayButtonLayout::paintPauseToCancel(Painter &p, const QBrush &brush, double progress) { static const auto sqrt2 = sqrt(2.); auto pauseLeft = 0. + _st.pausePosition.x(); @@ -253,7 +253,7 @@ void PlayButtonLayout::animationCallback() { _callback(); } -void PlayButtonLayout::startTransform(float64 from, float64 to) { +void PlayButtonLayout::startTransform(double from, double to) { _transformProgress.start([this] { animationCallback(); }, from, to, st::mediaPlayerButtonTransformDuration); } diff --git a/Telegram/SourceFiles/media/player/media_player_button.h b/Telegram/SourceFiles/media/player/media_player_button.h index 024fd823f..9670b9a01 100644 --- a/Telegram/SourceFiles/media/player/media_player_button.h +++ b/Telegram/SourceFiles/media/player/media_player_button.h @@ -41,12 +41,12 @@ public: private: void animationCallback(); - void startTransform(float64 from, float64 to); + void startTransform(double from, double to); void paintPlay(Painter &p, const QBrush &brush); - void paintPlayToPause(Painter &p, const QBrush &brush, float64 progress); - void paintPlayToCancel(Painter &p, const QBrush &brush, float64 progress); - void paintPauseToCancel(Painter &p, const QBrush &brush, float64 progress); + void paintPlayToPause(Painter &p, const QBrush &brush, double progress); + void paintPlayToCancel(Painter &p, const QBrush &brush, double progress); + void paintPauseToCancel(Painter &p, const QBrush &brush, double progress); const style::MediaPlayerButton &_st; diff --git a/Telegram/SourceFiles/media/player/media_player_cover.cpp b/Telegram/SourceFiles/media/player/media_player_cover.cpp index fae5c08dc..50f8fe8cb 100644 --- a/Telegram/SourceFiles/media/player/media_player_cover.cpp +++ b/Telegram/SourceFiles/media/player/media_player_cover.cpp @@ -90,14 +90,14 @@ CoverWidget::CoverWidget(QWidget *parent) : TWidget(parent) _playback->setInLoadingStateChangedCallback([this](bool loading) { _playbackSlider->setDisabled(loading); }); - _playback->setValueChangedCallback([this](float64 value) { + _playback->setValueChangedCallback([this](double value) { _playbackSlider->setValue(value); }); - _playbackSlider->setChangeProgressCallback([this](float64 value) { + _playbackSlider->setChangeProgressCallback([this](double value) { _playback->setValue(value, false); handleSeekProgress(value); }); - _playbackSlider->setChangeFinishedCallback([this](float64 value) { + _playbackSlider->setChangeFinishedCallback([this](double value) { _playback->setValue(value, false); handleSeekFinished(value); }); @@ -151,7 +151,7 @@ void CoverWidget::setCloseCallback(ButtonCallback &&callback) { _close->setClickedCallback(std::move(callback)); } -void CoverWidget::handleSeekProgress(float64 progress) { +void CoverWidget::handleSeekProgress(double progress) { if (!_lastDurationMs) return; auto positionMs = snap(static_cast(progress * _lastDurationMs), 0LL, _lastDurationMs); @@ -162,7 +162,7 @@ void CoverWidget::handleSeekProgress(float64 progress) { } } -void CoverWidget::handleSeekFinished(float64 progress) { +void CoverWidget::handleSeekFinished(double progress) { if (!_lastDurationMs) return; auto positionMs = snap(static_cast(progress * _lastDurationMs), 0LL, _lastDurationMs); @@ -274,7 +274,7 @@ void CoverWidget::handleSongUpdate(const TrackState &state) { void CoverWidget::updateTimeText(const TrackState &state) { QString time; - qint64 position = 0, length = 0, display = 0; + int64_t position = 0, length = 0, display = 0; auto frequency = state.frequency; if (!IsStoppedOrStopping(state.state)) { display = position = state.position; diff --git a/Telegram/SourceFiles/media/player/media_player_cover.h b/Telegram/SourceFiles/media/player/media_player_cover.h index 1efef7e90..0b949076d 100644 --- a/Telegram/SourceFiles/media/player/media_player_cover.h +++ b/Telegram/SourceFiles/media/player/media_player_cover.h @@ -55,8 +55,8 @@ protected: private: void setCloseVisible(bool visible); - void handleSeekProgress(float64 progress); - void handleSeekFinished(float64 progress); + void handleSeekProgress(double progress); + void handleSeekFinished(double progress); void updatePlayPrevNextPositions(); void updateLabelPositions(); diff --git a/Telegram/SourceFiles/media/player/media_player_float.cpp b/Telegram/SourceFiles/media/player/media_player_float.cpp index ab2657df5..f34bc383f 100644 --- a/Telegram/SourceFiles/media/player/media_player_float.cpp +++ b/Telegram/SourceFiles/media/player/media_player_float.cpp @@ -73,20 +73,20 @@ void Float::mouseMoveEvent(QMouseEvent *e) { } } -float64 Float::outRatio() const { +double Float::outRatio() const { auto parent = parentWidget()->rect(); auto min = 1.; if (x() < parent.x()) { - accumulate_min(min, 1. - (parent.x() - x()) / float64(width())); + accumulate_min(min, 1. - (parent.x() - x()) / double(width())); } if (y() < parent.y()) { - accumulate_min(min, 1. - (parent.y() - y()) / float64(height())); + accumulate_min(min, 1. - (parent.y() - y()) / double(height())); } if (x() + width() > parent.x() + parent.width()) { - accumulate_min(min, 1. - (x() + width() - parent.x() - parent.width()) / float64(width())); + accumulate_min(min, 1. - (x() + width() - parent.x() - parent.width()) / double(width())); } if (y() + height() > parent.y() + parent.height()) { - accumulate_min(min, 1. - (y() + height() - parent.y() - parent.height()) / float64(height())); + accumulate_min(min, 1. - (y() + height() - parent.y() - parent.height()) / double(height())); } return snap(min, 0., 1.); } @@ -239,7 +239,7 @@ void Float::updatePlayback() { if (_item) { if (!_roundPlayback) { _roundPlayback = std::make_unique(); - _roundPlayback->setValueChangedCallback([this](float64 value) { + _roundPlayback->setValueChangedCallback([this](double value) { update(); }); } diff --git a/Telegram/SourceFiles/media/player/media_player_float.h b/Telegram/SourceFiles/media/player/media_player_float.h index d175e36ca..1cb9a89c9 100644 --- a/Telegram/SourceFiles/media/player/media_player_float.h +++ b/Telegram/SourceFiles/media/player/media_player_float.h @@ -34,13 +34,13 @@ public: HistoryItem *item() const { return _item; } - void setOpacity(float64 opacity) { + void setOpacity(double opacity) { if (_opacity != opacity) { _opacity = opacity; update(); } } - float64 countOpacityByParent() const { + double countOpacityByParent() const { return outRatio(); } bool isReady() const { @@ -73,7 +73,7 @@ protected: void mouseDoubleClickEvent(QMouseEvent *e) override; private: - float64 outRatio() const; + double outRatio() const; Clip::Reader *getReader() const; void repaintItem(); void prepareShadow(); @@ -86,7 +86,7 @@ private: HistoryItem *_item = nullptr; base::lambda _toggleCallback; - float64 _opacity = 1.; + double _opacity = 1.; QPixmap _shadow; QImage _frame; diff --git a/Telegram/SourceFiles/media/player/media_player_volume_controller.cpp b/Telegram/SourceFiles/media/player/media_player_volume_controller.cpp index 53a62e183..8218e8e0e 100644 --- a/Telegram/SourceFiles/media/player/media_player_volume_controller.cpp +++ b/Telegram/SourceFiles/media/player/media_player_volume_controller.cpp @@ -34,10 +34,10 @@ namespace Player { VolumeController::VolumeController(QWidget *parent) : TWidget(parent) , _slider(this, st::mediaPlayerPanelPlayback) { _slider->setMoveByWheel(true); - _slider->setChangeProgressCallback([this](float64 volume) { + _slider->setChangeProgressCallback([this](double volume) { applyVolumeChange(volume); }); - _slider->setChangeFinishedCallback([this](float64 volume) { + _slider->setChangeFinishedCallback([this](double volume) { if (volume > 0) { Global::SetRememberedSongVolume(volume); } @@ -63,7 +63,7 @@ void VolumeController::resizeEvent(QResizeEvent *e) { _slider->setGeometry(rect()); } -void VolumeController::setVolume(float64 volume) { +void VolumeController::setVolume(double volume) { _slider->setValue(volume); if (volume > 0) { Global::SetRememberedSongVolume(volume); @@ -71,7 +71,7 @@ void VolumeController::setVolume(float64 volume) { applyVolumeChange(volume); } -void VolumeController::applyVolumeChange(float64 volume) { +void VolumeController::applyVolumeChange(double volume) { if (volume != Global::SongVolume()) { Global::SetSongVolume(volume); mixer()->setSongVolume(Global::SongVolume()); diff --git a/Telegram/SourceFiles/media/player/media_player_volume_controller.h b/Telegram/SourceFiles/media/player/media_player_volume_controller.h index 6156de467..78fd64327 100644 --- a/Telegram/SourceFiles/media/player/media_player_volume_controller.h +++ b/Telegram/SourceFiles/media/player/media_player_volume_controller.h @@ -38,8 +38,8 @@ protected: void resizeEvent(QResizeEvent *e) override; private: - void setVolume(float64 volume); - void applyVolumeChange(float64 volume); + void setVolume(double volume); + void applyVolumeChange(double volume); object_ptr _slider; diff --git a/Telegram/SourceFiles/media/player/media_player_widget.cpp b/Telegram/SourceFiles/media/player/media_player_widget.cpp index a8976c373..8230f9a83 100644 --- a/Telegram/SourceFiles/media/player/media_player_widget.cpp +++ b/Telegram/SourceFiles/media/player/media_player_widget.cpp @@ -104,17 +104,17 @@ Widget::Widget(QWidget *parent) : TWidget(parent) _playback->setInLoadingStateChangedCallback([this](bool loading) { _playbackSlider->setDisabled(loading); }); - _playback->setValueChangedCallback([this](float64 value) { + _playback->setValueChangedCallback([this](double value) { _playbackSlider->setValue(value); }); - _playbackSlider->setChangeProgressCallback([this](float64 value) { + _playbackSlider->setChangeProgressCallback([this](double value) { if (_type != AudioMsgId::Type::Song) { return; // Round video seek is not supported for now :( } _playback->setValue(value, false); handleSeekProgress(value); }); - _playbackSlider->setChangeFinishedCallback([this](float64 value) { + _playbackSlider->setChangeFinishedCallback([this](double value) { if (_type != AudioMsgId::Type::Song) { return; // Round video seek is not supported for now :( } @@ -233,7 +233,7 @@ void Widget::volumeWidgetCreated(VolumeWidget *widget) { Widget::~Widget() = default; -void Widget::handleSeekProgress(float64 progress) { +void Widget::handleSeekProgress(double progress) { if (!_lastDurationMs) return; auto positionMs = snap(static_cast(progress * _lastDurationMs), 0LL, _lastDurationMs); @@ -245,7 +245,7 @@ void Widget::handleSeekProgress(float64 progress) { } } -void Widget::handleSeekFinished(float64 progress) { +void Widget::handleSeekFinished(double progress) { if (!_lastDurationMs) return; auto positionMs = snap(static_cast(progress * _lastDurationMs), 0LL, _lastDurationMs); @@ -429,7 +429,7 @@ void Widget::handleSongUpdate(const TrackState &state) { void Widget::updateTimeText(const TrackState &state) { QString time; - qint64 position = 0, length = 0, display = 0; + int64_t position = 0, length = 0, display = 0; auto frequency = state.frequency; if (!IsStoppedOrStopping(state.state)) { display = position = state.position; diff --git a/Telegram/SourceFiles/media/player/media_player_widget.h b/Telegram/SourceFiles/media/player/media_player_widget.h index 75a93fd29..4b57f0b50 100644 --- a/Telegram/SourceFiles/media/player/media_player_widget.h +++ b/Telegram/SourceFiles/media/player/media_player_widget.h @@ -66,8 +66,8 @@ protected: void mouseReleaseEvent(QMouseEvent *e) override; private: - void handleSeekProgress(float64 progress); - void handleSeekFinished(float64 progress); + void handleSeekProgress(double progress); + void handleSeekFinished(double progress); int getLabelsLeft() const; int getLabelsRight() const; diff --git a/Telegram/SourceFiles/media/view/media_clip_controller.cpp b/Telegram/SourceFiles/media/view/media_clip_controller.cpp index 913e35a47..0080cb28b 100644 --- a/Telegram/SourceFiles/media/view/media_clip_controller.cpp +++ b/Telegram/SourceFiles/media/view/media_clip_controller.cpp @@ -43,31 +43,31 @@ Controller::Controller(QWidget *parent) : TWidget(parent) , _fadeAnimation(std::make_unique(this)) { _fadeAnimation->show(); _fadeAnimation->setFinishedCallback([this] { fadeFinished(); }); - _fadeAnimation->setUpdatedCallback([this](float64 opacity) { fadeUpdated(opacity); }); + _fadeAnimation->setUpdatedCallback([this](double opacity) { fadeUpdated(opacity); }); _volumeController->setVolume(Global::VideoVolume()); connect(_playPauseResume, SIGNAL(clicked()), this, SIGNAL(playPressed())); connect(_fullScreenToggle, SIGNAL(clicked()), this, SIGNAL(toFullScreenPressed())); - connect(_volumeController, SIGNAL(volumeChanged(float64)), this, SIGNAL(volumeChanged(float64))); + connect(_volumeController, SIGNAL(volumeChanged(double)), this, SIGNAL(volumeChanged(double))); _playback->setInLoadingStateChangedCallback([this](bool loading) { _playbackSlider->setDisabled(loading); }); - _playback->setValueChangedCallback([this](float64 value) { + _playback->setValueChangedCallback([this](double value) { _playbackSlider->setValue(value); }); - _playbackSlider->setChangeProgressCallback([this](float64 value) { + _playbackSlider->setChangeProgressCallback([this](double value) { _playback->setValue(value, false); handleSeekProgress(value); // This may destroy Controller. }); - _playbackSlider->setChangeFinishedCallback([this](float64 value) { + _playbackSlider->setChangeFinishedCallback([this](double value) { _playback->setValue(value, false); handleSeekFinished(value); }); } -void Controller::handleSeekProgress(float64 progress) { +void Controller::handleSeekProgress(double progress) { if (!_lastDurationMs) return; auto positionMs = snap(static_cast(progress * _lastDurationMs), 0LL, _lastDurationMs); @@ -78,7 +78,7 @@ void Controller::handleSeekProgress(float64 progress) { } } -void Controller::handleSeekFinished(float64 progress) { +void Controller::handleSeekFinished(double progress) { if (!_lastDurationMs) return; auto positionMs = snap(static_cast(progress * _lastDurationMs), 0LL, _lastDurationMs); @@ -109,7 +109,7 @@ void Controller::fadeFinished() { fadeUpdated(1.); } -void Controller::fadeUpdated(float64 opacity) { +void Controller::fadeUpdated(double opacity) { _playbackSlider->setFadeOpacity(opacity); } @@ -131,7 +131,7 @@ void Controller::updatePlayPauseResumeState(const Player::TrackState &state) { } void Controller::updateTimeTexts(const Player::TrackState &state) { - qint64 position = 0, length = state.length; + int64_t position = 0, length = state.length; if (Player::IsStoppedAtEnd(state.state)) { position = state.length; diff --git a/Telegram/SourceFiles/media/view/media_clip_controller.h b/Telegram/SourceFiles/media/view/media_clip_controller.h index b09fff187..34cddf103 100644 --- a/Telegram/SourceFiles/media/view/media_clip_controller.h +++ b/Telegram/SourceFiles/media/view/media_clip_controller.h @@ -59,7 +59,7 @@ signals: void pausePressed(); void seekProgress(TimeMs positionMs); void seekFinished(TimeMs positionMs); - void volumeChanged(float64 volume); + void volumeChanged(double volume); void toFullScreenPressed(); void fromFullScreenPressed(); @@ -69,13 +69,13 @@ protected: void mousePressEvent(QMouseEvent *e) override; private: - void handleSeekProgress(float64 progress); - void handleSeekFinished(float64 progress); + void handleSeekProgress(double progress); + void handleSeekFinished(double progress); template void startFading(Callback start); void fadeFinished(); - void fadeUpdated(float64 opacity); + void fadeUpdated(double opacity); void updatePlayPauseResumeState(const Player::TrackState &state); void updateTimeTexts(const Player::TrackState &state); diff --git a/Telegram/SourceFiles/media/view/media_clip_playback.cpp b/Telegram/SourceFiles/media/view/media_clip_playback.cpp index 9b3c2f1a2..8deab0c95 100644 --- a/Telegram/SourceFiles/media/view/media_clip_playback.cpp +++ b/Telegram/SourceFiles/media/view/media_clip_playback.cpp @@ -35,7 +35,7 @@ Playback::Playback() : _a_value(animation(this, &Playback::step_value)) { } void Playback::updateState(const Player::TrackState &state) { - qint64 position = 0, length = state.length; + int64_t position = 0, length = state.length; auto wasInLoadingState = _inLoadingState; if (wasInLoadingState) { @@ -58,10 +58,10 @@ void Playback::updateState(const Player::TrackState &state) { if (position > length) { progress = 1.; } else if (length) { - progress = snap(float64(position) / length, 0., 1.); + progress = snap(double(position) / length, 0., 1.); } auto animatedPosition = position + (state.frequency * kPlaybackAnimationDurationMs / 1000); - auto animatedProgress = length ? qMax(float64(animatedPosition) / length, 0.) : 0.; + auto animatedProgress = length ? qMax(double(animatedPosition) / length, 0.) : 0.; if (length != _length || position != _position || wasInLoadingState) { if (auto animated = (length && _length && animatedProgress > value())) { setValue(animatedProgress, animated); @@ -73,7 +73,7 @@ void Playback::updateState(const Player::TrackState &state) { } } -void Playback::updateLoadingState(float64 progress) { +void Playback::updateLoadingState(double progress) { if (!_inLoadingState) { _inLoadingState = true; if (_inLoadingStateChanged) { @@ -84,16 +84,16 @@ void Playback::updateLoadingState(float64 progress) { setValue(progress, animated); } -float64 Playback::value() const { +double Playback::value() const { return qMin(a_value.current(), 1.); } -float64 Playback::value(TimeMs ms) { +double Playback::value(TimeMs ms) { _a_value.step(ms); return value(); } -void Playback::setValue(float64 value, bool animated) { +void Playback::setValue(double value, bool animated) { if (animated) { a_value.start(value); _a_value.start(); @@ -106,7 +106,7 @@ void Playback::setValue(float64 value, bool animated) { } } -void Playback::step_value(float64 ms, bool timer) { +void Playback::step_value(double ms, bool timer) { auto dt = ms / kPlaybackAnimationDurationMs; if (dt >= 1.) { _a_value.stop(); diff --git a/Telegram/SourceFiles/media/view/media_clip_playback.h b/Telegram/SourceFiles/media/view/media_clip_playback.h index 4ff8444b0..27835d672 100644 --- a/Telegram/SourceFiles/media/view/media_clip_playback.h +++ b/Telegram/SourceFiles/media/view/media_clip_playback.h @@ -33,33 +33,33 @@ class Playback { public: Playback(); - void setValueChangedCallback(base::lambda callback) { + void setValueChangedCallback(base::lambda callback) { _valueChanged = std::move(callback); } void setInLoadingStateChangedCallback(base::lambda callback) { _inLoadingStateChanged = std::move(callback); } - void setValue(float64 value, bool animated); - float64 value() const; - float64 value(TimeMs ms); + void setValue(double value, bool animated); + double value() const; + double value(TimeMs ms); void updateState(const Player::TrackState &state); - void updateLoadingState(float64 progress); + void updateLoadingState(double progress); private: - void step_value(float64 ms, bool timer); + void step_value(double ms, bool timer); // This can animate for a very long time (like in music playing), // so it should be a BasicAnimation, not an Animation. anim::value a_value; BasicAnimation _a_value; - base::lambda _valueChanged; + base::lambda _valueChanged; bool _inLoadingState = false; base::lambda _inLoadingStateChanged; - int64 _position = 0; - int64 _length = 0; + int64_t _position = 0; + int64_t _length = 0; bool _playing = false; diff --git a/Telegram/SourceFiles/media/view/media_clip_volume_controller.cpp b/Telegram/SourceFiles/media/view/media_clip_volume_controller.cpp index e0e717d82..b276cfa23 100644 --- a/Telegram/SourceFiles/media/view/media_clip_volume_controller.cpp +++ b/Telegram/SourceFiles/media/view/media_clip_volume_controller.cpp @@ -31,7 +31,7 @@ VolumeController::VolumeController(QWidget *parent) : TWidget(parent) { setMouseTracking(true); } -void VolumeController::setVolume(float64 volume) { +void VolumeController::setVolume(double volume) { _volume = volume; update(); } @@ -39,10 +39,10 @@ void VolumeController::setVolume(float64 volume) { void VolumeController::paintEvent(QPaintEvent *e) { Painter p(this); - int32 top = st::mediaviewVolumeIconTop; - int32 left = (width() - st::mediaviewVolumeIcon.width()) / 2; - int32 mid = left + qRound(st::mediaviewVolumeIcon.width() * _volume); - int32 right = left + st::mediaviewVolumeIcon.width(); + int32_t top = st::mediaviewVolumeIconTop; + int32_t left = (width() - st::mediaviewVolumeIcon.width()) / 2; + int32_t mid = left + qRound(st::mediaviewVolumeIcon.width() * _volume); + int32_t right = left + st::mediaviewVolumeIcon.width(); if (mid > left) { p.setClipRect(rtlrect(left, top, mid - left, st::mediaviewVolumeIcon.height(), width())); @@ -68,8 +68,8 @@ void VolumeController::mouseMoveEvent(QMouseEvent *e) { } int delta = e->pos().x() - _downCoord; int left = (width() - st::mediaviewVolumeIcon.width()) / 2; - float64 startFrom = snap((_downCoord - left) / float64(st::mediaviewVolumeIcon.width()), 0., 1.); - float64 add = delta / float64(4 * st::mediaviewVolumeIcon.width()); + double startFrom = snap((_downCoord - left) / double(st::mediaviewVolumeIcon.width()), 0., 1.); + double add = delta / double(4 * st::mediaviewVolumeIcon.width()); auto newVolume = snap(startFrom + add, 0., 1.); changeVolume(newVolume); } @@ -77,11 +77,11 @@ void VolumeController::mouseMoveEvent(QMouseEvent *e) { void VolumeController::mousePressEvent(QMouseEvent *e) { _downCoord = snap(e->pos().x(), 0, width()); int left = (width() - st::mediaviewVolumeIcon.width()) / 2; - auto newVolume = snap((_downCoord - left) / float64(st::mediaviewVolumeIcon.width()), 0., 1.); + auto newVolume = snap((_downCoord - left) / double(st::mediaviewVolumeIcon.width()), 0., 1.); changeVolume(newVolume); } -void VolumeController::changeVolume(float64 newVolume) { +void VolumeController::changeVolume(double newVolume) { if (newVolume != _volume) { setVolume(newVolume); emit volumeChanged(_volume); diff --git a/Telegram/SourceFiles/media/view/media_clip_volume_controller.h b/Telegram/SourceFiles/media/view/media_clip_volume_controller.h index 0142cacb4..afc4d9b6e 100644 --- a/Telegram/SourceFiles/media/view/media_clip_volume_controller.h +++ b/Telegram/SourceFiles/media/view/media_clip_volume_controller.h @@ -29,10 +29,10 @@ class VolumeController : public TWidget { public: VolumeController(QWidget *parent); - void setVolume(float64 volume); + void setVolume(double volume); signals: - void volumeChanged(float64 volume); + void volumeChanged(double volume); protected: void paintEvent(QPaintEvent *e) override; @@ -44,9 +44,9 @@ protected: private: void setOver(bool over); - void changeVolume(float64 newVolume); + void changeVolume(double newVolume); - float64 _volume = 0.; + double _volume = 0.; int _downCoord = -1; // < 0 means mouse is not pressed bool _over = false; diff --git a/Telegram/SourceFiles/mediaview.cpp b/Telegram/SourceFiles/mediaview.cpp index f530946ff..81b3e36bd 100644 --- a/Telegram/SourceFiles/mediaview.cpp +++ b/Telegram/SourceFiles/mediaview.cpp @@ -303,15 +303,15 @@ void MediaView::updateDocSize() { if (!_doc || !fileBubbleShown()) return; if (_doc->loading()) { - quint64 ready = _doc->loadOffset(), total = _doc->size; + uint64_t ready = _doc->loadOffset(), total = _doc->size; QString readyStr, totalStr, mb; if (total >= 1024 * 1024) { // more than 1 mb - qint64 readyTenthMb = (ready * 10 / (1024 * 1024)), totalTenthMb = (total * 10 / (1024 * 1024)); + int64_t readyTenthMb = (ready * 10 / (1024 * 1024)), totalTenthMb = (total * 10 / (1024 * 1024)); readyStr = QString::number(readyTenthMb / 10) + '.' + QString::number(readyTenthMb % 10); totalStr = QString::number(totalTenthMb / 10) + '.' + QString::number(totalTenthMb % 10); mb = qsl("MB"); } else if (total >= 1024) { - qint64 readyKb = (ready / 1024), totalKb = (total / 1024); + int64_t readyKb = (ready / 1024), totalKb = (total / 1024); readyStr = QString::number(readyKb); totalStr = QString::number(totalKb); mb = qsl("KB"); @@ -325,7 +325,7 @@ void MediaView::updateDocSize() { _docSize = formatSizeText(_doc->size); } _docSizeWidth = st::mediaviewFont->width(_docSize); - int32 maxw = st::mediaviewFileSize.width() - st::mediaviewFileIconSize - st::mediaviewFilePadding * 3; + int32_t maxw = st::mediaviewFileSize.width() - st::mediaviewFileIconSize - st::mediaviewFilePadding * 3; if (_docSizeWidth > maxw) { _docSize = st::mediaviewFont->elided(_docSize, maxw); _docSizeWidth = st::mediaviewFont->width(_docSize); @@ -417,9 +417,9 @@ void MediaView::updateControls() { } if (!_caption.isEmpty()) { - int32 skipw = qMax(_dateNav.left() + _dateNav.width(), _headerNav.left() + _headerNav.width()); - int32 maxw = qMin(qMax(width() - 2 * skipw - st::mediaviewCaptionPadding.left() - st::mediaviewCaptionPadding.right() - 2 * st::mediaviewCaptionMargin.width(), int(st::msgMinWidth)), _caption.maxWidth()); - int32 maxh = qMin(_caption.countHeight(maxw), int(height() / 4 - st::mediaviewCaptionPadding.top() - st::mediaviewCaptionPadding.bottom() - 2 * st::mediaviewCaptionMargin.height())); + int32_t skipw = qMax(_dateNav.left() + _dateNav.width(), _headerNav.left() + _headerNav.width()); + int32_t maxw = qMin(qMax(width() - 2 * skipw - st::mediaviewCaptionPadding.left() - st::mediaviewCaptionPadding.right() - 2 * st::mediaviewCaptionMargin.width(), int(st::msgMinWidth)), _caption.maxWidth()); + int32_t maxh = qMin(_caption.countHeight(maxw), int(height() / 4 - st::mediaviewCaptionPadding.top() - st::mediaviewCaptionPadding.bottom() - 2 * st::mediaviewCaptionMargin.height())); _captionRect = QRect((width() - maxw) / 2, height() - maxh - st::mediaviewCaptionPadding.bottom() - st::mediaviewCaptionMargin.height(), maxw, maxh); } else { _captionRect = QRect(); @@ -474,7 +474,7 @@ void MediaView::step_state(TimeMs ms, bool timer) { case OverMore: update(_moreNav); break; default: break; } - float64 dt = float64(ms - start) / st::mediaviewFadeDuration; + double dt = double(ms - start) / st::mediaviewFadeDuration; if (dt >= 1) { _animOpacities.remove(i.key()); i = _animations.erase(i); @@ -484,7 +484,7 @@ void MediaView::step_state(TimeMs ms, bool timer) { } } if (_controlsState == ControlsShowing || _controlsState == ControlsHiding) { - float64 dt = float64(ms - _controlsAnimStarted) / (_controlsState == ControlsShowing ? st::mediaviewShowDuration : st::mediaviewHideDuration); + double dt = double(ms - _controlsAnimStarted) / (_controlsState == ControlsShowing ? st::mediaviewShowDuration : st::mediaviewHideDuration); if (dt >= 1) { a_cOpacity.finish(); _controlsState = (_controlsState == ControlsShowing ? ControlsShown : ControlsHidden); @@ -505,7 +505,7 @@ void MediaView::updateCursor() { setCursor(_controlsState == ControlsHidden ? Qt::BlankCursor : (_over == OverNone ? style::cur_default : style::cur_pointer)); } -float64 MediaView::radialProgress() const { +double MediaView::radialProgress() const { if (_doc) { return _doc->progress(); } else if (_photo) { @@ -574,7 +574,7 @@ void MediaView::step_radial(TimeMs ms, bool timer) { } void MediaView::zoomIn() { - int32 newZoom = _zoom; + int32_t newZoom = _zoom; if (newZoom == ZoomToScreenLevel) { if (qCeil(_zoomToScreen) <= MaxZoomLevel) { newZoom = qCeil(_zoomToScreen); @@ -590,7 +590,7 @@ void MediaView::zoomIn() { } void MediaView::zoomOut() { - int32 newZoom = _zoom; + int32_t newZoom = _zoom; if (newZoom == ZoomToScreenLevel) { if (qFloor(_zoomToScreen) >= -MaxZoomLevel) { newZoom = qFloor(_zoomToScreen); @@ -606,7 +606,7 @@ void MediaView::zoomOut() { } void MediaView::zoomReset() { - int32 newZoom = _zoom; + int32_t newZoom = _zoom; if (_zoom == 0) { if (qFloor(_zoomToScreen) == qCeil(_zoomToScreen) && qRound(_zoomToScreen) >= -MaxZoomLevel && qRound(_zoomToScreen) <= MaxZoomLevel) { newZoom = qRound(_zoomToScreen); @@ -618,7 +618,7 @@ void MediaView::zoomReset() { } _x = -_width / 2; _y = -((gifShown() ? _gif->height() : (_current.height() / cIntRetinaFactor())) / 2); - float64 z = (_zoom == ZoomToScreenLevel) ? _zoomToScreen : _zoom; + double z = (_zoom == ZoomToScreenLevel) ? _zoomToScreen : _zoom; if (z >= 0) { _x = qRound(_x * (z + 1)); _y = qRound(_y * (z + 1)); @@ -632,7 +632,7 @@ void MediaView::zoomReset() { zoomUpdate(newZoom); } -void MediaView::zoomUpdate(int32 &newZoom) { +void MediaView::zoomUpdate(int32_t &newZoom) { if (newZoom != ZoomToScreenLevel) { while ((newZoom < 0 && (-newZoom + 1) > _w) || (-newZoom + 1) > _h) { ++newZoom; @@ -1225,11 +1225,11 @@ void MediaView::displayPhoto(PhotoData *photo, HistoryItem *item) { moveToScreen(); } if (_w > width()) { - _h = qRound(_h * width() / float64(_w)); + _h = qRound(_h * width() / double(_w)); _w = width(); } if (_h > height()) { - _w = qRound(_w * height() / float64(_h)); + _w = qRound(_w * height() / double(_h)); _h = height(); } _x = (width() - _w) / 2; @@ -1303,12 +1303,12 @@ void MediaView::displayDocument(DocumentData *doc, HistoryItem *item) { // empty _docIconRect = QRect((width() - st::mediaviewFileIconSize) / 2, (height() - st::mediaviewFileIconSize) / 2, st::mediaviewFileIconSize, st::mediaviewFileIconSize); if (fileBubbleShown()) { if (!_doc || _doc->thumb->isNull()) { - int32 colorIndex = documentColorIndex(_doc, _docExt); + int32_t colorIndex = documentColorIndex(_doc, _docExt); _docIconColor = documentColor(colorIndex); const style::icon *(thumbs[]) = { &st::mediaviewFileBlue, &st::mediaviewFileGreen, &st::mediaviewFileRed, &st::mediaviewFileYellow }; _docIcon = thumbs[colorIndex]; - int32 extmaxw = (st::mediaviewFileIconSize - st::mediaviewFileExtPadding * 2); + int32_t extmaxw = (st::mediaviewFileIconSize - st::mediaviewFileExtPadding * 2); _docExtWidth = st::mediaviewFileExtFont->width(_docExt); if (_docExtWidth > extmaxw) { _docExt = st::mediaviewFileNameFont->elided(_docExt, extmaxw, Qt::ElideMiddle); @@ -1316,7 +1316,7 @@ void MediaView::displayDocument(DocumentData *doc, HistoryItem *item) { // empty } } else { _doc->thumb->load(); - int32 tw = _doc->thumb->width(), th = _doc->thumb->height(); + int32_t tw = _doc->thumb->width(), th = _doc->thumb->height(); if (!tw || !th) { _docThumbx = _docThumby = _docThumbw = 0; } else if (tw > th) { @@ -1330,7 +1330,7 @@ void MediaView::displayDocument(DocumentData *doc, HistoryItem *item) { // empty } } - int32 maxw = st::mediaviewFileSize.width() - st::mediaviewFileIconSize - st::mediaviewFilePadding * 3; + int32_t maxw = st::mediaviewFileSize.width() - st::mediaviewFileIconSize - st::mediaviewFilePadding * 3; if (_doc) { _docName = (_doc->type == StickerDocument) ? lang(lng_in_dlg_sticker) : (_doc->type == AnimatedDocument ? qsl("GIF") : (_doc->name.isEmpty() ? lang(lng_mediaview_doc_image) : _doc->name)); @@ -1362,9 +1362,9 @@ void MediaView::displayDocument(DocumentData *doc, HistoryItem *item) { // empty } _width = _w; if (_w > 0 && _h > 0) { - _zoomToScreen = float64(width()) / _w; + _zoomToScreen = double(width()) / _w; if (_h * _zoomToScreen > height()) { - _zoomToScreen = float64(height()) / _h; + _zoomToScreen = double(height()) / _h; } if (_zoomToScreen >= 1.) { _zoomToScreen -= 1.; @@ -1492,7 +1492,7 @@ void MediaView::initThemePreview() { if (!location.isEmpty() && location.accessEnable()) { _themePreviewShown = true; auto path = _doc->location().name(); - auto id = _themePreviewId = rand_value(); + auto id = _themePreviewId = rand_value(); auto ready = base::lambda_guarded(this, [this, id](std::unique_ptr result) { if (id != _themePreviewId) { return; @@ -1541,7 +1541,7 @@ void MediaView::createClipController() { connect(_clipController, SIGNAL(pausePressed()), this, SLOT(onVideoPauseResume())); connect(_clipController, SIGNAL(seekProgress(TimeMs)), this, SLOT(onVideoSeekProgress(TimeMs))); connect(_clipController, SIGNAL(seekFinished(TimeMs)), this, SLOT(onVideoSeekFinished(TimeMs))); - connect(_clipController, SIGNAL(volumeChanged(float64)), this, SLOT(onVideoVolumeChanged(float64))); + connect(_clipController, SIGNAL(volumeChanged(double)), this, SLOT(onVideoVolumeChanged(double))); connect(_clipController, SIGNAL(toFullScreenPressed()), this, SLOT(onVideoToggleFullScreen())); connect(_clipController, SIGNAL(fromFullScreenPressed()), this, SLOT(onVideoToggleFullScreen())); @@ -1615,7 +1615,7 @@ void MediaView::onVideoSeekFinished(TimeMs positionMs) { restartVideoAtSeekPosition(positionMs); } -void MediaView::onVideoVolumeChanged(float64 volume) { +void MediaView::onVideoVolumeChanged(double volume) { Global::SetVideoVolume(volume); updateMixerVideoVolume(); Global::RefVideoVolumeChanged().notify(); @@ -1711,19 +1711,19 @@ void MediaView::paintEvent(QPaintEvent *e) { // photo if (_photo) { - int32 w = _width * cIntRetinaFactor(); + int32_t w = _width * cIntRetinaFactor(); if (_full <= 0 && _photo->loaded()) { - int32 h = int((_photo->full->height() * (qreal(w) / qreal(_photo->full->width()))) + 0.9999); + int32_t h = int((_photo->full->height() * (qreal(w) / qreal(_photo->full->width()))) + 0.9999); _current = _photo->full->pixNoCache(w, h, Images::Option::Smooth); if (cRetina()) _current.setDevicePixelRatio(cRetinaFactor()); _full = 1; } else if (_full < 0 && _photo->medium->loaded()) { - int32 h = int((_photo->full->height() * (qreal(w) / qreal(_photo->full->width()))) + 0.9999); + int32_t h = int((_photo->full->height() * (qreal(w) / qreal(_photo->full->width()))) + 0.9999); _current = _photo->medium->pixNoCache(w, h, Images::Option::Smooth | Images::Option::Blurred); if (cRetina()) _current.setDevicePixelRatio(cRetinaFactor()); _full = 0; } else if (_current.isNull() && _photo->thumb->loaded()) { - int32 h = int((_photo->full->height() * (qreal(w) / qreal(_photo->full->width()))) + 0.9999); + int32_t h = int((_photo->full->height() * (qreal(w) / qreal(_photo->full->width()))) + 0.9999); _current = _photo->thumb->pixNoCache(w, h, Images::Option::Smooth | Images::Option::Blurred); if (cRetina()) _current.setDevicePixelRatio(cRetinaFactor()); } else if (_current.isNull()) { @@ -1747,7 +1747,7 @@ void MediaView::paintEvent(QPaintEvent *e) { } bool radial = false; - float64 radialOpacity = 0; + double radialOpacity = 0; if (_radial.animating()) { _radial.step(ms); radial = _radial.animating(); @@ -1776,12 +1776,12 @@ void MediaView::paintEvent(QPaintEvent *e) { if (_saveMsgStarted) { auto ms = getms(); - float64 dt = float64(ms) - _saveMsgStarted, hidingDt = dt - st::mediaviewSaveMsgShowing - st::mediaviewSaveMsgShown; + double dt = double(ms) - _saveMsgStarted, hidingDt = dt - st::mediaviewSaveMsgShowing - st::mediaviewSaveMsgShown; if (dt < st::mediaviewSaveMsgShowing + st::mediaviewSaveMsgShown + st::mediaviewSaveMsgHiding) { if (hidingDt >= 0 && _saveMsgOpacity.to() > 0.5) { _saveMsgOpacity.start(0); } - float64 progress = (hidingDt >= 0) ? (hidingDt / st::mediaviewSaveMsgHiding) : (dt / st::mediaviewSaveMsgShowing); + double progress = (hidingDt >= 0) ? (hidingDt / st::mediaviewSaveMsgHiding) : (dt / st::mediaviewSaveMsgShowing); _saveMsgOpacity.update(qMin(progress, 1.), anim::linear); if (_saveMsgOpacity.current() > 0) { p.setOpacity(_saveMsgOpacity.current()); @@ -1810,7 +1810,7 @@ void MediaView::paintEvent(QPaintEvent *e) { p.fillRect(_docRect, st::mediaviewFileBg); if (_docIconRect.intersects(r)) { bool radial = false; - float64 radialOpacity = 0; + double radialOpacity = 0; if (_radial.animating()) { _radial.step(ms); radial = _radial.animating(); @@ -1827,7 +1827,7 @@ void MediaView::paintEvent(QPaintEvent *e) { } } } else { - int32 rf(cIntRetinaFactor()); + int32_t rf(cIntRetinaFactor()); p.drawPixmap(_docIconRect.topLeft(), _doc->thumb->pix(_docThumbw), QRect(_docThumbx * rf, _docThumby * rf, st::mediaviewFileIconSize * rf, st::mediaviewFileIconSize * rf)); } @@ -1847,7 +1847,7 @@ void MediaView::paintEvent(QPaintEvent *e) { } } - float64 co = _fullScreenVideo ? 0. : a_cOpacity.current(); + double co = _fullScreenVideo ? 0. : a_cOpacity.current(); if (co > 0) { // left nav bar if (_leftNav.intersects(r) && _leftNavVisible) { @@ -1930,7 +1930,7 @@ void MediaView::paintEvent(QPaintEvent *e) { // name if (_from && _nameNav.intersects(r)) { - float64 o = overLevel(OverName); + double o = overLevel(OverName); p.setOpacity((o * st::mediaviewIconOverOpacity + (1 - o) * st::mediaviewIconOpacity) * co); _fromName.drawElided(p, _nameNav.left(), _nameNav.top(), _nameNav.width()); @@ -1942,7 +1942,7 @@ void MediaView::paintEvent(QPaintEvent *e) { // date if (_dateNav.intersects(r)) { - float64 o = overLevel(OverDate); + double o = overLevel(OverDate); p.setOpacity((o * st::mediaviewIconOverOpacity + (1 - o) * st::mediaviewIconOpacity) * co); p.drawText(_dateNav.left(), _dateNav.top() + st::mediaviewFont->ascent, _dateText); @@ -1971,8 +1971,8 @@ void MediaView::paintEvent(QPaintEvent *e) { } } -void MediaView::paintDocRadialLoading(Painter &p, bool radial, float64 radialOpacity) { - float64 o = overLevel(OverIcon); +void MediaView::paintDocRadialLoading(Painter &p, bool radial, double radialOpacity) { + double o = overLevel(OverIcon); if (radial || (_doc && !_doc->loaded())) { QRect inner(QPoint(_docIconRect.x() + ((_docIconRect.width() - st::radialSize.width()) / 2), _docIconRect.y() + ((_docIconRect.height() - st::radialSize.height()) / 2)), st::radialSize); @@ -2132,7 +2132,7 @@ void MediaView::wheelEvent(QWheelEvent *e) { void MediaView::setZoomLevel(int newZoom) { if (_zoom == newZoom) return; - float64 nx, ny, z = (_zoom == ZoomToScreenLevel) ? _zoomToScreen : _zoom; + double nx, ny, z = (_zoom == ZoomToScreenLevel) ? _zoomToScreen : _zoom; _w = gifShown() ? convertScale(_gif->width()) : (convertScale(_current.width()) / cIntRetinaFactor()); _h = gifShown() ? convertScale(_gif->height()) : (convertScale(_current.height()) / cIntRetinaFactor()); if (z >= 0) { @@ -2159,7 +2159,7 @@ void MediaView::setZoomLevel(int newZoom) { update(); } -bool MediaView::moveToNext(int32 delta) { +bool MediaView::moveToNext(int32_t delta) { if (_index < 0) { if (delta == -1 && _photo == _additionalChatPhoto) { auto lastChatPhoto = computeLastOverviewChatPhoto(); @@ -2193,7 +2193,7 @@ bool MediaView::moveToNext(int32 delta) { return true; } - int32 newIndex = _index + delta; + int32_t newIndex = _index + delta; if (_history && _overview != OverviewCount) { bool newMigrated = _msgmigrated; if (!newMigrated && newIndex < 0 && _migrated) { @@ -2249,7 +2249,7 @@ bool MediaView::moveToNext(int32 delta) { return true; } -void MediaView::preloadData(int32 delta) { +void MediaView::preloadData(int32_t delta) { int indexInOverview = _index; bool indexOfMigratedItem = _msgmigrated; if (_index < 0) { @@ -2288,9 +2288,9 @@ void MediaView::preloadData(int32 delta) { } } - for (int32 i = from; i <= to; ++i) { + for (int32_t i = from; i <= to; ++i) { History *previewHistory = indexOfMigratedItem ? _migrated : _history; - int32 previewIndex = i; + int32_t previewIndex = i; if (_migrated) { if (indexOfMigratedItem && previewIndex >= _migrated->overview(_overview).size()) { previewHistory = _history; @@ -2319,17 +2319,17 @@ void MediaView::preloadData(int32 delta) { } } } else if (_user) { - for (int32 i = from; i <= to; ++i) { + for (int32_t i = from; i <= to; ++i) { if (i >= 0 && i < _user->photos.size() && i != indexInOverview) { _user->photos[i]->thumb->load(); } } - for (int32 i = from; i <= to; ++i) { + for (int32_t i = from; i <= to; ++i) { if (i >= 0 && i < _user->photos.size() && i != indexInOverview) { _user->photos[i]->download(); } } - int32 forgetIndex = indexInOverview - delta * 2; + int32_t forgetIndex = indexInOverview - delta * 2; if (forgetIndex >= 0 && forgetIndex < _user->photos.size() && forgetIndex != indexInOverview) { _user->photos[forgetIndex]->forget(); } @@ -2393,8 +2393,8 @@ void MediaView::mouseDoubleClickEvent(QMouseEvent *e) { } void MediaView::snapXY() { - int32 xmin = width() - _w, xmax = 0; - int32 ymin = height() - _h, ymax = 0; + int32_t xmin = width() - _w, xmax = 0; + int32_t ymin = height() - _h, ymax = 0; if (xmin > (width() - _w) / 2) xmin = (width() - _w) / 2; if (xmax < (width() - _w) / 2) xmax = (width() - _w) / 2; if (ymin > (height() - _h) / 2) ymin = (height() - _h) / 2; @@ -2823,7 +2823,7 @@ void MediaView::loadBack() { } } } else if (_user && _user->photosCount != 0) { - int32 limit = (_index < MediaOverviewStartPerPage && _user->photos.size() > MediaOverviewStartPerPage) ? SearchPerPage : MediaOverviewStartPerPage; + int32_t limit = (_index < MediaOverviewStartPerPage && _user->photos.size() > MediaOverviewStartPerPage) ? SearchPerPage : MediaOverviewStartPerPage; _loadRequest = MTP::send(MTPphotos_GetUserPhotos(_user->inputUser, MTP_int(_user->photos.size()), MTP_long(0), MTP_int(limit)), rpcDone(&MediaView::userPhotosLoaded, _user)); } } @@ -2903,7 +2903,7 @@ void MediaView::userPhotosLoaded(UserData *u, const MTPphotos_Photos &photos, mt } void MediaView::updateHeader() { - int32 index = _index, count = 0, addcount = (_migrated && _overview != OverviewCount) ? _migrated->overviewCount(_overview) : 0; + int32_t index = _index, count = 0, addcount = (_migrated && _overview != OverviewCount) ? _migrated->overviewCount(_overview) : 0; if (_history) { if (_overview != OverviewCount) { bool lastOverviewPhotoLoaded = (!_history->overview(_overview).isEmpty() || ( @@ -2952,7 +2952,7 @@ void MediaView::updateHeader() { } } _headerHasLink = _history && typeHasMediaOverview(_overview); - int32 hwidth = st::mediaviewThickFont->width(_headerText); + int32_t hwidth = st::mediaviewThickFont->width(_headerText); if (hwidth > width() / 3) { hwidth = width() / 3; _headerText = st::mediaviewThickFont->elided(_headerText, hwidth, Qt::ElideMiddle); @@ -2960,7 +2960,7 @@ void MediaView::updateHeader() { _headerNav = myrtlrect(st::mediaviewTextLeft, height() - st::mediaviewHeaderTop, hwidth, st::mediaviewThickFont->height); } -float64 MediaView::overLevel(OverState control) const { +double MediaView::overLevel(OverState control) const { auto i = _animOpacities.constFind(control); return (i == _animOpacities.cend()) ? (_over == control ? 1 : 0) : i->current(); } diff --git a/Telegram/SourceFiles/mediaview.h b/Telegram/SourceFiles/mediaview.h index b75eac532..efa7bedbd 100644 --- a/Telegram/SourceFiles/mediaview.h +++ b/Telegram/SourceFiles/mediaview.h @@ -62,8 +62,8 @@ public: void showPhoto(PhotoData *photo, PeerData *context); void showDocument(DocumentData *doc, HistoryItem *context); void moveToScreen(); - bool moveToNext(int32 delta); - void preloadData(int32 delta); + bool moveToNext(int32_t delta); + void preloadData(int32_t delta); void leaveToChildEvent(QEvent *e, QWidget *child) override { // e -- from enterEvent() of child TWidget updateOverState(OverNone); @@ -131,7 +131,7 @@ private slots: void onVideoPauseResume(); void onVideoSeekProgress(TimeMs positionMs); void onVideoSeekFinished(TimeMs positionMs); - void onVideoVolumeChanged(float64 volume); + void onVideoVolumeChanged(double volume); void onVideoToggleFullScreen(); void onVideoPlayProgress(const AudioMsgId &audioId); @@ -187,7 +187,7 @@ private: void changingMsgId(HistoryItem *row, MsgId newId); // Radial animation interface. - float64 radialProgress() const; + double radialProgress() const; bool radialLoading() const; QRect radialRect() const; void radialStart(); @@ -215,14 +215,14 @@ private: void zoomIn(); void zoomOut(); void zoomReset(); - void zoomUpdate(int32 &newZoom); + void zoomUpdate(int32_t &newZoom); - void paintDocRadialLoading(Painter &p, bool radial, float64 radialOpacity); + void paintDocRadialLoading(Painter &p, bool radial, double radialOpacity); void paintThemePreview(Painter &p, QRect clip); void updateOverRect(OverState state); bool updateOverState(OverState newState); - float64 overLevel(OverState control) const; + double overLevel(OverState control) const; MsgId getMsgIdFromOverview(not_null history, int index) const; @@ -256,13 +256,13 @@ private: int _x = 0, _y = 0, _w = 0, _h = 0; int _xStart = 0, _yStart = 0; int _zoom = 0; // < 0 - out, 0 - none, > 0 - in - float64 _zoomToScreen = 0.; // for documents + double _zoomToScreen = 0.; // for documents QPoint _mStart; bool _pressed = false; - int32 _dragging = 0; + int32_t _dragging = 0; QPixmap _current; Media::Clip::ReaderPointer _gif; - int32 _full = -1; // -1 - thumb, 0 - medium, 1 - full + int32_t _full = -1; // -1 - thumb, 0 - medium, 1 - full // Video without audio stream playback information. bool _videoIsSilent = false; @@ -270,7 +270,7 @@ private: bool _videoStopped = false; TimeMs _videoPositionMs = 0; TimeMs _videoDurationMs = 0; - int32 _videoFrequencyMs = 1000; // 1000 ms per second. + int32_t _videoFrequencyMs = 1000; // 1000 ms per second. bool fileShown() const; bool gifShown() const; @@ -368,7 +368,7 @@ private: int _verticalWheelDelta = 0; bool _themePreviewShown = false; - uint64 _themePreviewId = 0; + uint64_t _themePreviewId = 0; QRect _themePreviewRect; std::unique_ptr _themePreview; object_ptr _themeApply = { nullptr }; diff --git a/Telegram/SourceFiles/messenger.cpp b/Telegram/SourceFiles/messenger.cpp index d7043c3e2..77721f87d 100644 --- a/Telegram/SourceFiles/messenger.cpp +++ b/Telegram/SourceFiles/messenger.cpp @@ -292,18 +292,18 @@ void Messenger::setMtpKey(MTP::DcId dcId, const MTP::AuthKey::Data &keyData) { QByteArray Messenger::serializeMtpAuthorization() const { auto serialize = [this](auto mainDcId, auto &keys, auto &keysToDestroy) { auto keysSize = [](auto &list) { - return sizeof(qint32) + list.size() * (sizeof(qint32) + MTP::AuthKey::Data().size()); + return sizeof(int32_t) + list.size() * (sizeof(int32_t) + MTP::AuthKey::Data().size()); }; auto writeKeys = [](QDataStream &stream, auto &keys) { - stream << qint32(keys.size()); + stream << int32_t(keys.size()); for (auto &key : keys) { - stream << qint32(key->dcId()); + stream << int32_t(key->dcId()); key->write(stream); } }; auto result = QByteArray(); - auto size = sizeof(qint32) + sizeof(qint32); // userId + mainDcId + auto size = sizeof(int32_t) + sizeof(int32_t); // userId + mainDcId size += keysSize(keys) + keysSize(keysToDestroy); result.reserve(size); { @@ -311,7 +311,7 @@ QByteArray Messenger::serializeMtpAuthorization() const { stream.setVersion(QDataStream::Qt_5_1); auto currentUserId = _authSession ? _authSession->userId() : 0; - stream << qint32(currentUserId) << qint32(mainDcId); + stream << int32_t(currentUserId) << int32_t(mainDcId); writeKeys(stream, keys); writeKeys(stream, keysToDestroy); @@ -354,8 +354,8 @@ void Messenger::setMtpAuthorization(const QByteArray &serialized) { QDataStream stream(serialized); stream.setVersion(QDataStream::Qt_5_1); - auto userId = Serialize::read(stream); - auto mainDcId = Serialize::read(stream); + auto userId = Serialize::read(stream); + auto mainDcId = Serialize::read(stream); if (stream.status() != QDataStream::Ok) { LOG(("MTP Error: could not read main fields from serialized mtp authorization.")); return; @@ -365,14 +365,14 @@ void Messenger::setMtpAuthorization(const QByteArray &serialized) { _private->mtpConfig.mainDcId = mainDcId; auto readKeys = [&stream](auto &keys) { - auto count = Serialize::read(stream); + auto count = Serialize::read(stream); if (stream.status() != QDataStream::Ok) { LOG(("MTP Error: could not read keys count from serialized mtp authorization.")); return; } keys.reserve(count); for (auto i = 0; i != count; ++i) { - auto dcId = Serialize::read(stream); + auto dcId = Serialize::read(stream); auto keyData = Serialize::read(stream); if (stream.status() != QDataStream::Ok) { LOG(("MTP Error: could not read key from serialized mtp authorization.")); @@ -391,7 +391,7 @@ void Messenger::startMtp() { _mtproto = std::make_unique(_dcOptions.get(), MTP::Instance::Mode::Normal, base::take(_private->mtpConfig)); _private->mtpConfig.mainDcId = _mtproto->mainDcId(); - _mtproto->setStateChangedHandler([](MTP::ShiftedDcId shiftedDcId, int32 state) { + _mtproto->setStateChangedHandler([](MTP::ShiftedDcId shiftedDcId, int32_t state) { if (App::wnd()) { App::wnd()->mtpStateChanged(shiftedDcId, state); } @@ -874,7 +874,7 @@ void Messenger::uploadProfilePhoto(const QImage &tosend, const PeerId &peerId) { auto photo = MTP_photo(MTP_flags(0), MTP_long(id), MTP_long(0), MTP_int(unixtime()), MTP_vector(photoSizes)); QString file, filename; - int32 filesize = 0; + int32_t filesize = 0; QByteArray data; SendMediaReady ready(SendMediaType::Photo, file, filename, filesize, data, id, id, qsl("jpg"), peerId, photo, photoThumbs, MTP_documentEmpty(MTP_long(0)), jpeg, 0); diff --git a/Telegram/SourceFiles/mtproto/auth_key.cpp b/Telegram/SourceFiles/mtproto/auth_key.cpp index 24d7f13a2..89cec5054 100644 --- a/Telegram/SourceFiles/mtproto/auth_key.cpp +++ b/Telegram/SourceFiles/mtproto/auth_key.cpp @@ -25,7 +25,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org namespace MTP { void AuthKey::prepareAES_oldmtp(const MTPint128 &msgKey, MTPint256 &aesKey, MTPint256 &aesIV, bool send) const { - uint32 x = send ? 0 : 8; + uint32_t x = send ? 0 : 8; uchar data_a[16 + 32], sha1_a[20]; memcpy(data_a, &msgKey, 16); @@ -60,7 +60,7 @@ void AuthKey::prepareAES_oldmtp(const MTPint128 &msgKey, MTPint256 &aesKey, MTPi } void AuthKey::prepareAES(const MTPint128 &msgKey, MTPint256 &aesKey, MTPint256 &aesIV, bool send) const { - uint32 x = send ? 0 : 8; + uint32_t x = send ? 0 : 8; uchar data_a[16 + 36], sha256_a[32]; memcpy(data_a, &msgKey, 16); @@ -82,7 +82,7 @@ void AuthKey::prepareAES(const MTPint128 &msgKey, MTPint256 &aesKey, MTPint256 & memcpy(iv + 8 + 16, sha256_b + 24, 8); } -void aesIgeEncryptRaw(const void *src, void *dst, uint32 len, const void *key, const void *iv) { +void aesIgeEncryptRaw(const void *src, void *dst, uint32_t len, const void *key, const void *iv) { uchar aes_key[32], aes_iv[32]; memcpy(aes_key, key, 32); memcpy(aes_iv, iv, 32); @@ -92,7 +92,7 @@ void aesIgeEncryptRaw(const void *src, void *dst, uint32 len, const void *key, c AES_ige_encrypt(static_cast(src), static_cast(dst), len, &aes, aes_iv, AES_ENCRYPT); } -void aesIgeDecryptRaw(const void *src, void *dst, uint32 len, const void *key, const void *iv) { +void aesIgeDecryptRaw(const void *src, void *dst, uint32_t len, const void *key, const void *iv) { uchar aes_key[32], aes_iv[32]; memcpy(aes_key, key, 32); memcpy(aes_iv, iv, 32); @@ -102,7 +102,7 @@ void aesIgeDecryptRaw(const void *src, void *dst, uint32 len, const void *key, c AES_ige_encrypt(static_cast(src), static_cast(dst), len, &aes, aes_iv, AES_DECRYPT); } -void aesCtrEncrypt(void *data, uint32 len, const void *key, CTRState *state) { +void aesCtrEncrypt(void *data, uint32_t len, const void *key, CTRState *state) { AES_KEY aes; AES_set_encrypt_key(static_cast(key), 256, &aes); diff --git a/Telegram/SourceFiles/mtproto/auth_key.h b/Telegram/SourceFiles/mtproto/auth_key.h index 1b46c562d..5a4077936 100644 --- a/Telegram/SourceFiles/mtproto/auth_key.h +++ b/Telegram/SourceFiles/mtproto/auth_key.h @@ -29,7 +29,7 @@ class AuthKey { public: static constexpr auto kSize = 256; // 2048 bits. using Data = std::array; - using KeyId = uint64; + using KeyId = uint64_t; enum class Type { Generated, @@ -103,45 +103,45 @@ private: using AuthKeyPtr = std::shared_ptr; using AuthKeysList = std::vector; -void aesIgeEncryptRaw(const void *src, void *dst, uint32 len, const void *key, const void *iv); -void aesIgeDecryptRaw(const void *src, void *dst, uint32 len, const void *key, const void *iv); +void aesIgeEncryptRaw(const void *src, void *dst, uint32_t len, const void *key, const void *iv); +void aesIgeDecryptRaw(const void *src, void *dst, uint32_t len, const void *key, const void *iv); -inline void aesIgeEncrypt_oldmtp(const void *src, void *dst, uint32 len, const AuthKeyPtr &authKey, const MTPint128 &msgKey) { +inline void aesIgeEncrypt_oldmtp(const void *src, void *dst, uint32_t len, const AuthKeyPtr &authKey, const MTPint128 &msgKey) { MTPint256 aesKey, aesIV; authKey->prepareAES_oldmtp(msgKey, aesKey, aesIV, true); return aesIgeEncryptRaw(src, dst, len, static_cast(&aesKey), static_cast(&aesIV)); } -inline void aesIgeEncrypt(const void *src, void *dst, uint32 len, const AuthKeyPtr &authKey, const MTPint128 &msgKey) { +inline void aesIgeEncrypt(const void *src, void *dst, uint32_t len, const AuthKeyPtr &authKey, const MTPint128 &msgKey) { MTPint256 aesKey, aesIV; authKey->prepareAES(msgKey, aesKey, aesIV, true); return aesIgeEncryptRaw(src, dst, len, static_cast(&aesKey), static_cast(&aesIV)); } -inline void aesEncryptLocal(const void *src, void *dst, uint32 len, const AuthKeyPtr &authKey, const void *key128) { +inline void aesEncryptLocal(const void *src, void *dst, uint32_t len, const AuthKeyPtr &authKey, const void *key128) { MTPint256 aesKey, aesIV; authKey->prepareAES_oldmtp(*(const MTPint128*)key128, aesKey, aesIV, false); return aesIgeEncryptRaw(src, dst, len, static_cast(&aesKey), static_cast(&aesIV)); } -inline void aesIgeDecrypt_oldmtp(const void *src, void *dst, uint32 len, const AuthKeyPtr &authKey, const MTPint128 &msgKey) { +inline void aesIgeDecrypt_oldmtp(const void *src, void *dst, uint32_t len, const AuthKeyPtr &authKey, const MTPint128 &msgKey) { MTPint256 aesKey, aesIV; authKey->prepareAES_oldmtp(msgKey, aesKey, aesIV, false); return aesIgeDecryptRaw(src, dst, len, static_cast(&aesKey), static_cast(&aesIV)); } -inline void aesIgeDecrypt(const void *src, void *dst, uint32 len, const AuthKeyPtr &authKey, const MTPint128 &msgKey) { +inline void aesIgeDecrypt(const void *src, void *dst, uint32_t len, const AuthKeyPtr &authKey, const MTPint128 &msgKey) { MTPint256 aesKey, aesIV; authKey->prepareAES(msgKey, aesKey, aesIV, false); return aesIgeDecryptRaw(src, dst, len, static_cast(&aesKey), static_cast(&aesIV)); } -inline void aesDecryptLocal(const void *src, void *dst, uint32 len, const AuthKeyPtr &authKey, const void *key128) { +inline void aesDecryptLocal(const void *src, void *dst, uint32_t len, const AuthKeyPtr &authKey, const void *key128) { MTPint256 aesKey, aesIV; authKey->prepareAES_oldmtp(*(const MTPint128*)key128, aesKey, aesIV, false); @@ -155,9 +155,9 @@ struct CTRState { static constexpr int EcountSize = 16; uchar ivec[IvecSize] = { 0 }; - uint32 num = 0; + uint32_t num = 0; uchar ecount[EcountSize] = { 0 }; }; -void aesCtrEncrypt(void *data, uint32 len, const void *key, CTRState *state); +void aesCtrEncrypt(void *data, uint32_t len, const void *key, CTRState *state); } // namespace MTP diff --git a/Telegram/SourceFiles/mtproto/config_loader.cpp b/Telegram/SourceFiles/mtproto/config_loader.cpp index 6ac65de5e..c6e4d2bb7 100644 --- a/Telegram/SourceFiles/mtproto/config_loader.cpp +++ b/Telegram/SourceFiles/mtproto/config_loader.cpp @@ -143,7 +143,7 @@ void ConfigLoader::sendSpecialRequest() { } auto weak = base::make_weak_unique(this); - auto index = rand_value() % uint32(_specialEndpoints.size()); + auto index = rand_value() % uint32_t(_specialEndpoints.size()); auto endpoint = _specialEndpoints.begin() + index; _specialEnumCurrent = specialToRealDcId(endpoint->dcId); _instance->dcOptions()->constructAddOne(_specialEnumCurrent, MTPDdcOption::Flag::f_tcpo_only, endpoint->ip, endpoint->port); diff --git a/Telegram/SourceFiles/mtproto/connection.cpp b/Telegram/SourceFiles/mtproto/connection.cpp index a9c1d8713..96cf08190 100644 --- a/Telegram/SourceFiles/mtproto/connection.cpp +++ b/Telegram/SourceFiles/mtproto/connection.cpp @@ -187,10 +187,10 @@ ModExpFirst CreateModExp(int g, base::const_byte_span primeBytes, base::const_by return result; } -void wrapInvokeAfter(mtpRequest &to, const mtpRequest &from, const mtpRequestMap &haveSent, int32 skipBeforeRequest = 0) { +void wrapInvokeAfter(mtpRequest &to, const mtpRequest &from, const mtpRequestMap &haveSent, int32_t skipBeforeRequest = 0) { mtpMsgId afterId(*(mtpMsgId*)(from->after->data() + 4)); mtpRequestMap::const_iterator i = afterId ? haveSent.constFind(afterId) : haveSent.cend(); - int32 size = to->size(), lenInInts = (from.innerLength() >> 2), headlen = 4, fulllen = headlen + lenInInts; + int32_t size = to->size(), lenInInts = (from.innerLength() >> 2), headlen = 4, fulllen = headlen + lenInInts; if (i == haveSent.constEnd()) { // no invoke after or such msg was not sent or was completed recently to->resize(size + fulllen + skipBeforeRequest); if (skipBeforeRequest) { @@ -213,17 +213,17 @@ void wrapInvokeAfter(mtpRequest &to, const mtpRequest &from, const mtpRequestMap bool parsePQ(const QByteArray &pqStr, QByteArray &pStr, QByteArray &qStr) { if (pqStr.length() > 8) return false; // more than 64 bit pq - uint64 pq = 0, p, q; + uint64_t pq = 0, p, q; const uchar *pqChars = (const uchar*)pqStr.constData(); - for (uint32 i = 0, l = pqStr.length(); i < l; ++i) { + for (uint32_t i = 0, l = pqStr.length(); i < l; ++i) { pq <<= 8; - pq |= (uint64)pqChars[i]; + pq |= (uint64_t)pqChars[i]; } - uint64 pqSqrt = (uint64)sqrtl((long double)pq), ySqr, y; + uint64_t pqSqrt = (uint64_t)sqrtl((long double)pq), ySqr, y; while (pqSqrt * pqSqrt > pq) --pqSqrt; while (pqSqrt * pqSqrt < pq) ++pqSqrt; for (ySqr = pqSqrt * pqSqrt - pq; ; ++pqSqrt, ySqr = pqSqrt * pqSqrt - pq) { - y = (uint64)sqrtl((long double)ySqr); + y = (uint64_t)sqrtl((long double)ySqr); while (y * y > ySqr) --y; while (y * y < ySqr) ++y; if (!ySqr || y + pqSqrt >= pq) return false; @@ -237,14 +237,14 @@ bool parsePQ(const QByteArray &pqStr, QByteArray &pStr, QByteArray &qStr) { pStr.resize(4); uchar *pChars = (uchar*)pStr.data(); - for (uint32 i = 0; i < 4; ++i) { + for (uint32_t i = 0; i < 4; ++i) { *(pChars + 3 - i) = (uchar)(p & 0xFF); p >>= 8; } qStr.resize(4); uchar *qChars = (uchar*)qStr.data(); - for (uint32 i = 0; i < 4; ++i) { + for (uint32_t i = 0; i < 4; ++i) { *(qChars + 3 - i) = (uchar)(q & 0xFF); q >>= 8; } @@ -283,7 +283,7 @@ void Connection::waitTillFinish() { thread.reset(); } -int32 Connection::state() const { +int32_t Connection::state() const { Expects(data != nullptr && thread != nullptr); return data->getState(); @@ -307,13 +307,13 @@ void ConnectionPrivate::createConn(bool createIPv4, bool createIPv6) { if (createIPv4) { QWriteLocker lock(&stateConnMutex); _conn4 = AbstractConnection::create(_dcType, thread()); - connect(_conn4, SIGNAL(error(qint32)), this, SLOT(onError4(qint32))); + connect(_conn4, SIGNAL(error(int32_t)), this, SLOT(onError4(int32_t))); connect(_conn4, SIGNAL(receivedSome()), this, SLOT(onReceivedSome())); } if (createIPv6) { QWriteLocker lock(&stateConnMutex); _conn6 = AbstractConnection::create(_dcType, thread()); - connect(_conn6, SIGNAL(error(qint32)), this, SLOT(onError6(qint32))); + connect(_conn6, SIGNAL(error(int32_t)), this, SLOT(onError6(int32_t))); connect(_conn6, SIGNAL(receivedSome()), this, SLOT(onReceivedSome())); } firstSentAt = 0; @@ -334,7 +334,7 @@ void ConnectionPrivate::destroyConn(AbstractConnection **conn) { toDisconnect = *conn; disconnect(*conn, SIGNAL(connected()), nullptr, nullptr); disconnect(*conn, SIGNAL(disconnected()), nullptr, nullptr); - disconnect(*conn, SIGNAL(error(qint32)), nullptr, nullptr); + disconnect(*conn, SIGNAL(error(int32_t)), nullptr, nullptr); disconnect(*conn, SIGNAL(receivedData()), nullptr, nullptr); disconnect(*conn, SIGNAL(receivedSome()), nullptr, nullptr); *conn = nullptr; @@ -384,7 +384,7 @@ ConnectionPrivate::ConnectionPrivate(Instance *instance, QThread *thread, Connec connect(sessionData->owner(), SIGNAL(needToRestart()), this, SLOT(restartNow()), Qt::QueuedConnection); connect(this, SIGNAL(needToReceive()), sessionData->owner(), SLOT(tryToReceive()), Qt::QueuedConnection); - connect(this, SIGNAL(stateChanged(qint32)), sessionData->owner(), SLOT(onConnectionStateChange(qint32)), Qt::QueuedConnection); + connect(this, SIGNAL(stateChanged(int32_t)), sessionData->owner(), SLOT(onConnectionStateChange(int32_t)), Qt::QueuedConnection); connect(sessionData->owner(), SIGNAL(needToSend()), this, SLOT(tryToSend()), Qt::QueuedConnection); connect(sessionData->owner(), SIGNAL(needToPing()), this, SLOT(onPingSendForce()), Qt::QueuedConnection); connect(this, SIGNAL(sessionResetDone()), sessionData->owner(), SLOT(onResetDone()), Qt::QueuedConnection); @@ -392,16 +392,16 @@ ConnectionPrivate::ConnectionPrivate(Instance *instance, QThread *thread, Connec static bool _registered = false; if (!_registered) { _registered = true; - qRegisterMetaType >("QVector"); + qRegisterMetaType >("QVector"); } connect(this, SIGNAL(needToSendAsync()), sessionData->owner(), SLOT(needToResumeAndSend()), Qt::QueuedConnection); - connect(this, SIGNAL(sendAnythingAsync(qint64)), sessionData->owner(), SLOT(sendAnything(qint64)), Qt::QueuedConnection); + connect(this, SIGNAL(sendAnythingAsync(int64_t)), sessionData->owner(), SLOT(sendAnything(int64_t)), Qt::QueuedConnection); connect(this, SIGNAL(sendHttpWaitAsync()), sessionData->owner(), SLOT(sendAnything()), Qt::QueuedConnection); - connect(this, SIGNAL(sendPongAsync(quint64,quint64)), sessionData->owner(), SLOT(sendPong(quint64,quint64)), Qt::QueuedConnection); - connect(this, SIGNAL(sendMsgsStateInfoAsync(quint64, QByteArray)), sessionData->owner(), SLOT(sendMsgsStateInfo(quint64,QByteArray)), Qt::QueuedConnection); - connect(this, SIGNAL(resendAsync(quint64,qint64,bool,bool)), sessionData->owner(), SLOT(resend(quint64,qint64,bool,bool)), Qt::QueuedConnection); - connect(this, SIGNAL(resendManyAsync(QVector,qint64,bool,bool)), sessionData->owner(), SLOT(resendMany(QVector,qint64,bool,bool)), Qt::QueuedConnection); + connect(this, SIGNAL(sendPongAsync(uint64_t,uint64_t)), sessionData->owner(), SLOT(sendPong(uint64_t,uint64_t)), Qt::QueuedConnection); + connect(this, SIGNAL(sendMsgsStateInfoAsync(uint64_t, QByteArray)), sessionData->owner(), SLOT(sendMsgsStateInfo(uint64_t,QByteArray)), Qt::QueuedConnection); + connect(this, SIGNAL(resendAsync(uint64_t,int64_t,bool,bool)), sessionData->owner(), SLOT(resend(uint64_t,int64_t,bool,bool)), Qt::QueuedConnection); + connect(this, SIGNAL(resendManyAsync(QVector,int64_t,bool,bool)), sessionData->owner(), SLOT(resendMany(QVector,int64_t,bool,bool)), Qt::QueuedConnection); connect(this, SIGNAL(resendAllAsync()), sessionData->owner(), SLOT(resendAll())); } @@ -413,16 +413,16 @@ void ConnectionPrivate::onCDNConfigLoaded() { restart(); } -int32 ConnectionPrivate::getShiftedDcId() const { +int32_t ConnectionPrivate::getShiftedDcId() const { return _shiftedDcId; } -int32 ConnectionPrivate::getState() const { +int32_t ConnectionPrivate::getState() const { QReadLocker lock(&stateConnMutex); - int32 result = _state; + int32_t result = _state; if (_state < 0) { if (retryTimer.isActive()) { - result = int32(getms(true) - retryWillFinish); + result = int32_t(getms(true) - retryWillFinish); if (result >= 0) { result = -1; } @@ -441,7 +441,7 @@ QString ConnectionPrivate::transport() const { return result; } -bool ConnectionPrivate::setState(int32 state, int32 ifState) { +bool ConnectionPrivate::setState(int32_t state, int32_t ifState) { if (ifState != Connection::UpdateAlways) { QReadLocker lock(&stateConnMutex); if (_state != ifState) return false; @@ -526,7 +526,7 @@ void ConnectionPrivate::resetSession() { // recreate all msg_id and msg_seqno } } - uint64 session = rand_value(); + uint64_t session = rand_value(); DEBUG_LOG(("MTP Info: creating new session after bad_msg_notification, setting random server_session %1").arg(session)); sessionData->setSession(session); @@ -558,7 +558,7 @@ void ConnectionPrivate::resetSession() { // recreate all msg_id and msg_seqno for (mtpRequestMap::const_iterator i = haveSent.cbegin(), e = haveSent.cend(); i != e; ++i) { // replace msgIds in saved containers if (mtpRequestData::isSentContainer(i.value())) { mtpMsgId *ids = (mtpMsgId *)(i.value()->data() + 8); - for (uint32 j = 0, l = (i.value()->size() - 8) >> 1; j < l; ++j) { + for (uint32_t j = 0, l = (i.value()->size() - 8) >> 1; j < l; ++j) { Replaces::const_iterator k = replaces.constFind(ids[j]); if (k != replaces.cend()) { ids[j] = k.value(); @@ -643,7 +643,7 @@ mtpMsgId ConnectionPrivate::replaceMsgId(mtpRequest &request, mtpMsgId newId) { mtpRequest req(k.value()); if (mtpRequestData::isSentContainer(req)) { mtpMsgId *ids = (mtpMsgId *)(req->data() + 8); - for (uint32 i = 0, l = (req->size() - 8) >> 1; i < l; ++i) { + for (uint32_t i = 0, l = (req->size() - 8) >> 1; i < l; ++i) { if (ids[i] == oldMsgId) { ids[i] = newId; } @@ -664,7 +664,7 @@ mtpMsgId ConnectionPrivate::placeToContainer(mtpRequest &toSendRequest, mtpMsgId if (msgId >= bigMsgId) bigMsgId = msgid(); *(haveSentArr++) = msgId; - uint32 from = toSendRequest->size(), len = mtpRequestData::messageSize(req); + uint32_t from = toSendRequest->size(), len = mtpRequestData::messageSize(req); toSendRequest->resize(from + len); memcpy(toSendRequest->data() + from, req->constData() + 4, len * sizeof(mtpPrime)); @@ -678,7 +678,7 @@ void ConnectionPrivate::tryToSend() { } bool needsLayer = !sessionData->layerWasInited(); - int32 state = getState(); + int32_t state = getState(); bool prependOnly = (state != ConnectedState); mtpRequest pingRequest; if (_shiftedDcId == bareDcId(_shiftedDcId)) { // main session @@ -689,13 +689,13 @@ void ConnectionPrivate::tryToSend() { if (_pingIdToSend) { if (prependOnly || _shiftedDcId != bareDcId(_shiftedDcId)) { MTPPing ping(MTPping(MTP_long(_pingIdToSend))); - uint32 pingSize = ping.innerLength() >> 2; // copy from Session::send + uint32_t pingSize = ping.innerLength() >> 2; // copy from Session::send pingRequest = mtpRequestData::prepare(pingSize); ping.write(*pingRequest); DEBUG_LOG(("MTP Info: sending ping, ping_id: %1").arg(_pingIdToSend)); } else { MTPPing_delay_disconnect ping(MTP_long(_pingIdToSend), MTP_int(MTPPingDelayDisconnect)); - uint32 pingSize = ping.innerLength() >> 2; // copy from Session::send + uint32_t pingSize = ping.innerLength() >> 2; // copy from Session::send pingRequest = mtpRequestData::prepare(pingSize); ping.write(*pingRequest); DEBUG_LOG(("MTP Info: sending ping_delay_disconnect, ping_id: %1").arg(_pingIdToSend)); @@ -777,7 +777,7 @@ void ConnectionPrivate::tryToSend() { } MTPInitConnection initWrapper; - int32 initSize = 0, initSizeInInts = 0; + int32_t initSize = 0, initSizeInInts = 0; if (needsLayer) { auto systemLangCode = sessionData->systemLangCode(); auto cloudLangCode = sessionData->cloudLangCode(); @@ -797,7 +797,7 @@ void ConnectionPrivate::tryToSend() { mtpPreRequestMap toSendDummy, &toSend(prependOnly ? toSendDummy : sessionData->toSendMap()); if (prependOnly) locker1.unlock(); - uint32 toSendCount = toSend.size(); + uint32_t toSendCount = toSend.size(); if (pingRequest) ++toSendCount; if (ackRequest) ++toSendCount; if (resendRequest) ++toSendCount; @@ -832,7 +832,7 @@ void ConnectionPrivate::tryToSend() { if (needsLayer && !toSendRequest->needsLayer) needsLayer = false; if (toSendRequest->after) { - int32 toSendSize = toSendRequest.innerLength() >> 2; + int32_t toSendSize = toSendRequest.innerLength() >> 2; mtpRequest wrappedRequest(mtpRequestData::prepare(toSendSize, toSendSize + 3)); // cons + msg_id wrappedRequest->resize(4); memcpy(wrappedRequest->data(), toSendRequest->constData(), 4 * sizeof(mtpPrime)); @@ -840,7 +840,7 @@ void ConnectionPrivate::tryToSend() { toSendRequest = wrappedRequest; } if (needsLayer) { - int32 noWrapSize = (toSendRequest.innerLength() >> 2), toSendSize = noWrapSize + initSizeInInts; + int32_t noWrapSize = (toSendRequest.innerLength() >> 2), toSendSize = noWrapSize + initSizeInInts; mtpRequest wrappedRequest(mtpRequestData::prepare(toSendSize)); memcpy(wrappedRequest->data(), toSendRequest->constData(), 7 * sizeof(mtpPrime)); // all except length wrappedRequest->push_back(mtpc_invokeWithLayer); @@ -859,7 +859,7 @@ void ConnectionPrivate::tryToSend() { } } else { // send in container bool willNeedInit = false; - uint32 containerSize = 1 + 1, idsWrapSize = (toSendCount << 1); // cons + vector size, idsWrapSize - size of "request-like" wrap for msgId vector + uint32_t containerSize = 1 + 1, idsWrapSize = (toSendCount << 1); // cons + vector size, idsWrapSize - size of "request-like" wrap for msgId vector if (pingRequest) containerSize += mtpRequestData::messageSize(pingRequest); if (ackRequest) containerSize += mtpRequestData::messageSize(ackRequest); if (resendRequest) containerSize += mtpRequestData::messageSize(resendRequest); @@ -912,7 +912,7 @@ void ConnectionPrivate::tryToSend() { if (req->requestId) { if (mtpRequestData::needAck(req)) { req->msDate = mtpRequestData::isStateRequest(req) ? 0 : getms(true); - int32 reqNeedsLayer = (needsLayer && req->needsLayer) ? toSendRequest->size() : 0; + int32_t reqNeedsLayer = (needsLayer && req->needsLayer) ? toSendRequest->size() : 0; if (req->after) { wrapInvokeAfter(toSendRequest, req, haveSent, reqNeedsLayer ? initSizeInInts : 0); if (reqNeedsLayer) { @@ -936,7 +936,7 @@ void ConnectionPrivate::tryToSend() { } } if (!added) { - uint32 from = toSendRequest->size(), len = mtpRequestData::messageSize(req); + uint32_t from = toSendRequest->size(), len = mtpRequestData::messageSize(req); toSendRequest->resize(from + len); memcpy(toSendRequest->data() + from, req->constData() + 4, len * sizeof(mtpPrime)); } @@ -1102,12 +1102,12 @@ void ConnectionPrivate::restart() { setState(-retryTimeout); } -void ConnectionPrivate::onSentSome(uint64 size) { +void ConnectionPrivate::onSentSome(uint64_t size) { if (!_waitForReceivedTimer.isActive()) { - auto remain = static_cast(_waitForReceived); + auto remain = static_cast(_waitForReceived); if (!oldConnection) { auto remainBySize = size * _waitForReceived / 8192; // 8kb / sec, so 512 kb give 64 sec - remain = snap(remainBySize, remain, uint64(MTPMaxReceiveDelay)); + remain = snap(remainBySize, remain, uint64_t(MTPMaxReceiveDelay)); if (remain != _waitForReceived) { DEBUG_LOG(("Checking connect for request with size %1 bytes, delay will be %2").arg(size).arg(remain)); } @@ -1130,10 +1130,10 @@ void ConnectionPrivate::onReceivedSome() { oldConnectionTimer.start(MTPConnectionOldTimeout); _waitForReceivedTimer.stop(); if (firstSentAt > 0) { - int32 ms = getms(true) - firstSentAt; + int32_t ms = getms(true) - firstSentAt; DEBUG_LOG(("MTP Info: response in %1ms, _waitForReceived: %2ms").arg(ms).arg(_waitForReceived)); - if (ms > 0 && ms * 2 < int32(_waitForReceived)) _waitForReceived = qMax(ms * 2, int32(MTPMinReceiveDelay)); + if (ms > 0 && ms * 2 < int32_t(_waitForReceived)) _waitForReceived = qMax(ms * 2, int32_t(MTPMinReceiveDelay)); firstSentAt = -1; } } @@ -1268,7 +1268,7 @@ void ConnectionPrivate::handleReceived() { constexpr auto kEncryptedHeaderIntsCount = 8U; // 2 salt, 2 session, 2 msg_id, 1 seq_no, 1 length constexpr auto kMinimalEncryptedIntsCount = kEncryptedHeaderIntsCount + 4U; // + 1 data + 3 padding constexpr auto kMinimalIntsCount = kExternalHeaderIntsCount + kMinimalEncryptedIntsCount; - auto intsCount = uint32(intsBuffer.size()); + auto intsCount = uint32_t(intsBuffer.size()); auto ints = intsBuffer.constData(); if ((intsCount < kMinimalIntsCount) || (intsCount > kMaxMessageLength / kIntSize)) { LOG(("TCP Error: bad message received, len %1").arg(intsCount * kIntSize)); @@ -1276,8 +1276,8 @@ void ConnectionPrivate::handleReceived() { return restartOnError(); } - if (keyId != *(uint64*)ints) { - LOG(("TCP Error: bad auth_key_id %1 instead of %2 received").arg(keyId).arg(*(uint64*)ints)); + if (keyId != *(uint64_t*)ints) { + LOG(("TCP Error: bad auth_key_id %1 instead of %2 received").arg(keyId).arg(*(uint64_t*)ints)); TCP_LOG(("TCP Error: bad message %1").arg(Logs::mb(ints, intsCount * kIntSize).str())); return restartOnError(); @@ -1296,13 +1296,13 @@ void ConnectionPrivate::handleReceived() { #endif // TDESKTOP_MTPROTO_OLD auto decryptedInts = reinterpret_cast(decryptedBuffer.constData()); - auto serverSalt = *(uint64*)&decryptedInts[0]; - auto session = *(uint64*)&decryptedInts[2]; - auto msgId = *(uint64*)&decryptedInts[4]; - auto seqNo = *(uint32*)&decryptedInts[6]; + auto serverSalt = *(uint64_t*)&decryptedInts[0]; + auto session = *(uint64_t*)&decryptedInts[2]; + auto msgId = *(uint64_t*)&decryptedInts[4]; + auto seqNo = *(uint32_t*)&decryptedInts[6]; auto needAck = ((seqNo & 0x01) != 0); - auto messageLength = *(uint32*)&decryptedInts[7]; + auto messageLength = *(uint32_t*)&decryptedInts[7]; if (messageLength > kMaxMessageLength) { LOG(("TCP Error: bad messageLength %1").arg(messageLength)); TCP_LOG(("TCP Error: bad message %1").arg(Logs::mb(ints, intsCount * kIntSize).str())); @@ -1313,7 +1313,7 @@ void ConnectionPrivate::handleReceived() { auto fullDataLength = kEncryptedHeaderIntsCount * kIntSize + messageLength; // Without padding. // Can underflow, but it is an unsigned type, so we just check the range later. - auto paddingSize = static_cast(encryptedBytesCount) - static_cast(fullDataLength); + auto paddingSize = static_cast(encryptedBytesCount) - static_cast(fullDataLength); #ifdef TDESKTOP_MTPROTO_OLD constexpr auto kMinPaddingSize_oldmtp = 0U; @@ -1361,7 +1361,7 @@ void ConnectionPrivate::handleReceived() { TCP_LOG(("TCP Info: decrypted message %1,%2,%3 is %4 len").arg(msgId).arg(seqNo).arg(Logs::b(needAck)).arg(fullDataLength)); - uint64 serverSession = sessionData->getSession(); + uint64_t serverSession = sessionData->getSession(); if (session != serverSession) { LOG(("MTP Error: bad server session received")); TCP_LOG(("MTP Error: bad server session %1 instead of %2 in message received").arg(session).arg(serverSession)); @@ -1369,7 +1369,7 @@ void ConnectionPrivate::handleReceived() { return restartOnError(); } - int32 serverTime((int32)(msgId >> 32)), clientTime(unixtime()); + int32_t serverTime((int32_t)(msgId >> 32)), clientTime(unixtime()); bool isReply = ((msgId & 0x03) == 1); if (!isReply && ((msgId & 0x03) != 3)) { LOG(("MTP Error: bad msg_id %1 in message received").arg(msgId)); @@ -1378,7 +1378,7 @@ void ConnectionPrivate::handleReceived() { } bool badTime = false; - uint64 mySalt = sessionData->getSalt(); + uint64_t mySalt = sessionData->getSalt(); if (serverTime > clientTime + 60 || serverTime + 300 < clientTime) { DEBUG_LOG(("MTP Info: bad server time from msg_id: %1, my time: %2").arg(serverTime).arg(clientTime)); badTime = true; @@ -1424,7 +1424,7 @@ void ConnectionPrivate::handleReceived() { } // send acks - uint32 toAckSize = ackRequestData.size(); + uint32_t toAckSize = ackRequestData.size(); if (toAckSize) { DEBUG_LOG(("MTP Info: will send %1 acks, ids: %2").arg(toAckSize).arg(Logs::vector(ackRequestData))); emit sendAnythingAsync(MTPAckSendWaiting); @@ -1466,7 +1466,7 @@ void ConnectionPrivate::handleReceived() { } } -ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPrime *from, const mtpPrime *end, uint64 msgId, int32 serverTime, uint64 serverSalt, bool badTime) { +ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPrime *from, const mtpPrime *end, uint64_t msgId, int32_t serverTime, uint64_t serverSalt, bool badTime) { mtpTypeId cons = *from; try { @@ -1485,9 +1485,9 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr if (++from >= end) throw mtpErrorInsufficient(); const mtpPrime *otherEnd; - uint32 msgsCount = (uint32)*(from++); + uint32_t msgsCount = (uint32_t)*(from++); DEBUG_LOG(("Message Info: container received, count: %1").arg(msgsCount)); - for (uint32 i = 0; i < msgsCount; ++i) { + for (uint32_t i = 0; i < msgsCount; ++i) { if (from + 4 >= end) throw mtpErrorInsufficient(); otherEnd = from + 4; @@ -1538,7 +1538,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr MTPMsgsAck msg; msg.read(from, end); auto &ids = msg.c_msgs_ack().vmsg_ids.v; - uint32 idsCount = ids.size(); + uint32_t idsCount = ids.size(); DEBUG_LOG(("Message Info: acks received, ids: %1").arg(Logs::vector(ids))); if (!idsCount) return (badTime ? HandleResult::Ignored : HandleResult::Success); @@ -1563,7 +1563,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr if (resendId == _pingMsgId) { _pingId = 0; } - int32 errorCode = data.verror_code.v; + int32_t errorCode = data.verror_code.v; if (errorCode == 16 || errorCode == 17 || errorCode == 32 || errorCode == 33 || errorCode == 64) { // can handle bool needResend = (errorCode == 16 || errorCode == 17); // bad msg_id if (errorCode == 64) { // bad container! @@ -1585,7 +1585,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr if (mtpRequestData::isSentContainer(request)) { QStringList lst; const mtpMsgId *ids = (const mtpMsgId *)(request->constData() + 8); - for (uint32 i = 0, l = (request->size() - 8) >> 1; i < l; ++i) { + for (uint32_t i = 0, l = (request->size() - 8) >> 1; i < l; ++i) { lst.push_back(QString::number(ids[i])); } LOG(("Message Info: bad container received! messages: %1").arg(lst.join(','))); @@ -1644,7 +1644,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr return (badTime ? HandleResult::Ignored : HandleResult::Success); } - uint64 serverSalt = data.vnew_server_salt.v; + uint64_t serverSalt = data.vnew_server_salt.v; sessionData->setSalt(serverSalt); unixtimeSet(serverTime); @@ -1684,9 +1684,9 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr const mtpRequestIdsMap &wereAcked(sessionData->wereAckedMap()); mtpRequestIdsMap::const_iterator wereAckedEnd(wereAcked.cend()); - for (uint32 i = 0, l = idsCount; i < l; ++i) { + for (uint32_t i = 0, l = idsCount; i < l; ++i) { char state = 0; - uint64 reqMsgId = ids[i].v; + uint64_t reqMsgId = ids[i].v; if (reqMsgId < minRecv) { state |= 0x01; } else if (reqMsgId > maxRecv) { @@ -1853,8 +1853,8 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr DEBUG_LOG(("Message Info: resend of msgs requested, ids: %1").arg(Logs::vector(ids))); if (!idsCount) return (badTime ? HandleResult::Ignored : HandleResult::Success); - QVector toResend(ids.size()); - for (int32 i = 0, l = ids.size(); i < l; ++i) { + QVector toResend(ids.size()); + for (int32_t i = 0, l = ids.size(); i < l; ++i) { toResend[i] = ids.at(i).v; } resendMany(toResend, 0, false, true); @@ -1931,7 +1931,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr sessionData->setSalt(data.vserver_salt.v); mtpMsgId firstMsgId = data.vfirst_msg_id.v; - QVector toResend; + QVector toResend; { QReadLocker locker(sessionData->haveSentMutex()); const mtpRequestMap &haveSent(sessionData->haveSentMap()); @@ -2020,7 +2020,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr mtpBuffer ConnectionPrivate::ungzip(const mtpPrime *from, const mtpPrime *end) const { MTPstring packed; packed.read(from, end); // read packed string as serialized mtp string type - uint32 packedLen = packed.v.size(), unpackedChunk = packedLen, unpackedLen = 0; + uint32_t packedLen = packed.v.size(), unpackedChunk = packedLen, unpackedLen = 0; mtpBuffer result; // * 4 because of mtpPrime type result.resize(0); @@ -2052,7 +2052,7 @@ mtpBuffer ConnectionPrivate::ungzip(const mtpPrime *from, const mtpPrime *end) c } } if (stream.avail_out & 0x03) { - uint32 badSize = result.size() * sizeof(mtpPrime) - stream.avail_out; + uint32_t badSize = result.size() * sizeof(mtpPrime) - stream.avail_out; LOG(("RPC Error: bad length of unpacked data %1").arg(badSize)); DEBUG_LOG(("RPC Error: bad unpacked data %1").arg(Logs::mb(result.data(), badSize).str())); return mtpBuffer(); @@ -2065,10 +2065,10 @@ mtpBuffer ConnectionPrivate::ungzip(const mtpPrime *from, const mtpPrime *end) c return result; } -bool ConnectionPrivate::requestsFixTimeSalt(const QVector &ids, int32 serverTime, uint64 serverSalt) { - uint32 idsCount = ids.size(); +bool ConnectionPrivate::requestsFixTimeSalt(const QVector &ids, int32_t serverTime, uint64_t serverSalt) { + uint32_t idsCount = ids.size(); - for (uint32 i = 0; i < idsCount; ++i) { + for (uint32_t i = 0; i < idsCount; ++i) { if (wasSent(ids[i].v)) {// found such msg_id in recent acked requests or in recent sent requests if (serverSalt) sessionData->setSalt(serverSalt); unixtimeSet(serverTime, true); @@ -2079,7 +2079,7 @@ bool ConnectionPrivate::requestsFixTimeSalt(const QVector &ids, int32 s } void ConnectionPrivate::requestsAcked(const QVector &ids, bool byResponse) { - uint32 idsCount = ids.size(); + uint32_t idsCount = ids.size(); DEBUG_LOG(("Message Info: requests acked, ids %1").arg(Logs::vector(ids))); @@ -2093,16 +2093,16 @@ void ConnectionPrivate::requestsAcked(const QVector &ids, bool byRespon QWriteLocker locker2(sessionData->haveSentMutex()); mtpRequestMap &haveSent(sessionData->haveSentMap()); - for (uint32 i = 0; i < idsCount; ++i) { + for (uint32_t i = 0; i < idsCount; ++i) { mtpMsgId msgId = ids[i].v; mtpRequestMap::iterator req = haveSent.find(msgId); if (req != haveSent.cend()) { if (!req.value()->msDate) { DEBUG_LOG(("Message Info: container ack received, msgId %1").arg(ids[i].v)); - uint32 inContCount = ((*req)->size() - 8) / 2; + uint32_t inContCount = ((*req)->size() - 8) / 2; const mtpMsgId *inContId = (const mtpMsgId *)(req.value()->constData() + 8); toAckMore.reserve(toAckMore.size() + inContCount); - for (uint32 j = 0; j < inContCount; ++j) { + for (uint32_t j = 0; j < inContCount; ++j) { toAckMore.push_back(MTP_long(*(inContId++))); } haveSent.erase(req); @@ -2156,7 +2156,7 @@ void ConnectionPrivate::requestsAcked(const QVector &ids, bool byRespon } } - uint32 ackedCount = wereAcked.size(); + uint32_t ackedCount = wereAcked.size(); if (ackedCount > MTPIdsBufferSize) { DEBUG_LOG(("Message Info: removing some old acked sent msgIds %1").arg(ackedCount - MTPIdsBufferSize)); clearedAcked.reserve(ackedCount - MTPIdsBufferSize); @@ -2178,7 +2178,7 @@ void ConnectionPrivate::requestsAcked(const QVector &ids, bool byRespon } void ConnectionPrivate::handleMsgsStates(const QVector &ids, const QByteArray &states, QVector &acked) { - uint32 idsCount = ids.size(); + uint32_t idsCount = ids.size(); if (!idsCount) { DEBUG_LOG(("Message Info: void ids vector in handleMsgsStates()")); return; @@ -2189,9 +2189,9 @@ void ConnectionPrivate::handleMsgsStates(const QVector &ids, const QByt } acked.reserve(acked.size() + idsCount); - for (uint32 i = 0, count = idsCount; i < count; ++i) { + for (uint32_t i = 0, count = idsCount; i < count; ++i) { char state = states[i]; - uint64 requestMsgId = ids[i].v; + uint64_t requestMsgId = ids[i].v; { QReadLocker locker(sessionData->haveSentMutex()); const mtpRequestMap &haveSent(sessionData->haveSentMap()); @@ -2203,9 +2203,9 @@ void ConnectionPrivate::handleMsgsStates(const QVector &ids, const QByt mtpRequestIdsMap::iterator reqIt = toResend.find(requestMsgId); if (reqIt != toResend.cend()) { if ((state & 0x07) != 0x04) { // was received - DEBUG_LOG(("Message Info: state was received for msgId %1, state %2, already resending in container").arg(requestMsgId).arg((int32)state)); + DEBUG_LOG(("Message Info: state was received for msgId %1, state %2, already resending in container").arg(requestMsgId).arg((int32_t)state)); } else { - DEBUG_LOG(("Message Info: state was received for msgId %1, state %2, ack, cancelling resend").arg(requestMsgId).arg((int32)state)); + DEBUG_LOG(("Message Info: state was received for msgId %1, state %2, ack, cancelling resend").arg(requestMsgId).arg((int32_t)state)); acked.push_back(MTP_long(requestMsgId)); // will remove from resend in requestsAcked } } else { @@ -2215,22 +2215,22 @@ void ConnectionPrivate::handleMsgsStates(const QVector &ids, const QByt } } if ((state & 0x07) != 0x04) { // was received - DEBUG_LOG(("Message Info: state was received for msgId %1, state %2, resending in container").arg(requestMsgId).arg((int32)state)); + DEBUG_LOG(("Message Info: state was received for msgId %1, state %2, resending in container").arg(requestMsgId).arg((int32_t)state)); resend(requestMsgId, 10, true); } else { - DEBUG_LOG(("Message Info: state was received for msgId %1, state %2, ack").arg(requestMsgId).arg((int32)state)); + DEBUG_LOG(("Message Info: state was received for msgId %1, state %2, ack").arg(requestMsgId).arg((int32_t)state)); acked.push_back(MTP_long(requestMsgId)); } } } -void ConnectionPrivate::resend(quint64 msgId, qint64 msCanWait, bool forceContainer, bool sendMsgStateInfo) { +void ConnectionPrivate::resend(uint64_t msgId, int64_t msCanWait, bool forceContainer, bool sendMsgStateInfo) { if (msgId == _pingMsgId) return; emit resendAsync(msgId, msCanWait, forceContainer, sendMsgStateInfo); } -void ConnectionPrivate::resendMany(QVector msgIds, qint64 msCanWait, bool forceContainer, bool sendMsgStateInfo) { - for (int32 i = 0, l = msgIds.size(); i < l; ++i) { +void ConnectionPrivate::resendMany(QVector msgIds, int64_t msCanWait, bool forceContainer, bool sendMsgStateInfo) { + for (int32_t i = 0, l = msgIds.size(); i < l; ++i) { if (msgIds.at(i) == _pingMsgId) { msgIds.remove(i); --l; @@ -2312,7 +2312,7 @@ void ConnectionPrivate::updateAuthKey() { if (!sessionData || !_conn) return; DEBUG_LOG(("AuthKey Info: Connection updating key from Session, dc %1").arg(_shiftedDcId)); - uint64 newKeyId = 0; + uint64_t newKeyId = 0; { ReadLockerAttempt lock(sessionData->keyMutex()); if (!lock) { @@ -2483,14 +2483,14 @@ void ConnectionPrivate::dhParamsAnswered() { } auto &encDHStr = encDH.vencrypted_answer.v; - uint32 encDHLen = encDHStr.length(), encDHBufLen = encDHLen >> 2; + uint32_t encDHLen = encDHStr.length(), encDHBufLen = encDHLen >> 2; if ((encDHLen & 0x03) || encDHBufLen < 6) { LOG(("AuthKey Error: bad encrypted data length %1 (in server_DH_params_ok)!").arg(encDHLen)); DEBUG_LOG(("AuthKey Error: received encrypted data %1").arg(Logs::mb(encDHStr.constData(), encDHLen).str())); return restart(); } - uint32 nlen = _authKeyData->new_nonce.innerLength(), slen = _authKeyData->server_nonce.innerLength(); + uint32_t nlen = _authKeyData->new_nonce.innerLength(), slen = _authKeyData->server_nonce.innerLength(); uchar tmp_aes[1024], sha1ns[20], sha1sn[20], sha1nn[20]; memcpy(tmp_aes, &_authKeyData->new_nonce, nlen); memcpy(tmp_aes + nlen, &_authKeyData->server_nonce, slen); @@ -2680,7 +2680,7 @@ void ConnectionPrivate::dhClientParamsAnswered() { return restart(); } - uint64 salt1 = _authKeyData->new_nonce.l.l, salt2 = _authKeyData->server_nonce.l, serverSalt = salt1 ^ salt2; + uint64_t salt1 = _authKeyData->new_nonce.l.l, salt2 = _authKeyData->server_nonce.l, serverSalt = salt1 ^ salt2; sessionData->setSalt(serverSalt); auto authKey = std::make_shared(AuthKey::Type::Generated, bareDcId(_shiftedDcId), _authKeyStrings->auth_key); @@ -2771,7 +2771,7 @@ void ConnectionPrivate::authKeyCreated() { } } - _pingIdToSend = rand_value(); // get server_salt + _pingIdToSend = rand_value(); // get server_salt emit needToSendAsync(); } @@ -2803,7 +2803,7 @@ void ConnectionPrivate::clearAuthKeyData() { } } -void ConnectionPrivate::onError4(qint32 errorCode) { +void ConnectionPrivate::onError4(int32_t errorCode) { if (_conn && _conn == _conn6) return; // error in the unused if (errorCode == -429) { @@ -2816,7 +2816,7 @@ void ConnectionPrivate::onError4(qint32 errorCode) { } } -void ConnectionPrivate::onError6(qint32 errorCode) { +void ConnectionPrivate::onError6(int32_t errorCode) { if (_conn && _conn == _conn4) return; // error in the unused if (errorCode == -429) { @@ -2856,7 +2856,7 @@ template void ConnectionPrivate::sendRequestNotSecure(const TRequest &request) { try { mtpBuffer buffer; - uint32 requestSize = request.innerLength() >> 2; + uint32_t requestSize = request.innerLength() >> 2; buffer.resize(0); buffer.reserve(8 + requestSize); @@ -2902,12 +2902,12 @@ bool ConnectionPrivate::readResponseNotSecure(TResponse &response) { DEBUG_LOG(("AuthKey Error: answer bytes %1").arg(Logs::mb(answer, len * sizeof(mtpPrime)).str())); return false; } - if (answer[0] != 0 || answer[1] != 0 || (((uint32)answer[2]) & 0x03) != 1/* || (unixtime() - answer[3] > 300) || (answer[3] - unixtime() > 60)*/) { // didnt sync time yet + if (answer[0] != 0 || answer[1] != 0 || (((uint32_t)answer[2]) & 0x03) != 1/* || (unixtime() - answer[3] > 300) || (answer[3] - unixtime() > 60)*/) { // didnt sync time yet LOG(("AuthKey Error: bad request answer start (%1 %2 %3)").arg(answer[0]).arg(answer[1]).arg(answer[2])); DEBUG_LOG(("AuthKey Error: answer bytes %1").arg(Logs::mb(answer, len * sizeof(mtpPrime)).str())); return false; } - uint32 answerLen = (uint32)answer[4]; + uint32_t answerLen = (uint32_t)answer[4]; if (answerLen != (len - 5) * sizeof(mtpPrime)) { LOG(("AuthKey Error: bad request answer %1 <> %2").arg(answerLen).arg((len - 5) * sizeof(mtpPrime))); DEBUG_LOG(("AuthKey Error: answer bytes %1").arg(Logs::mb(answer, len * sizeof(mtpPrime)).str())); @@ -2922,7 +2922,7 @@ bool ConnectionPrivate::readResponseNotSecure(TResponse &response) { } bool ConnectionPrivate::sendRequest(mtpRequest &request, bool needAnyResponse, QReadLocker &lockFinished) { - uint32 fullSize = request->size(); + uint32_t fullSize = request->size(); if (fullSize < 9) return false; auto messageSize = mtpRequestData::messageSize(request); @@ -2956,7 +2956,7 @@ bool ConnectionPrivate::sendRequest(mtpRequest &request, bool needAnyResponse, Q MTP_LOG(_shiftedDcId, ("Send: ") + mtpTextSerialize(from, from + messageSize)); #ifdef TDESKTOP_MTPROTO_OLD - uint32 padding = fullSize - 4 - messageSize; + uint32_t padding = fullSize - 4 - messageSize; uchar encryptedSHA[20]; MTPint128 &msgKey(*(MTPint128*)(encryptedSHA + 4)); @@ -2964,7 +2964,7 @@ bool ConnectionPrivate::sendRequest(mtpRequest &request, bool needAnyResponse, Q mtpBuffer result; result.resize(9 + fullSize); - *((uint64*)&result[2]) = keyId; + *((uint64_t*)&result[2]) = keyId; *((MTPint128*)&result[4]) = msgKey; aesIgeEncrypt_oldmtp(request->constData(), &result[8], fullSize * sizeof(mtpPrime), key, msgKey); @@ -2980,7 +2980,7 @@ bool ConnectionPrivate::sendRequest(mtpRequest &request, bool needAnyResponse, Q mtpBuffer result; result.resize(9 + fullSize); - *((uint64*)&result[2]) = keyId; + *((uint64_t*)&result[2]) = keyId; *((MTPint128*)&result[4]) = msgKey; aesIgeEncrypt(request->constData(), &result[8], fullSize * sizeof(mtpPrime), key, msgKey); diff --git a/Telegram/SourceFiles/mtproto/connection.h b/Telegram/SourceFiles/mtproto/connection.h index fa317c62b..1402a00a3 100644 --- a/Telegram/SourceFiles/mtproto/connection.h +++ b/Telegram/SourceFiles/mtproto/connection.h @@ -79,7 +79,7 @@ public: static const int UpdateAlways = 666; - int32 state() const; + int32_t state() const; QString transport() const; private: @@ -98,24 +98,24 @@ public: void stop(); - int32 getShiftedDcId() const; + int32_t getShiftedDcId() const; - int32 getState() const; + int32_t getState() const; QString transport() const; signals: void needToReceive(); void needToRestart(); - void stateChanged(qint32 newState); + void stateChanged(int32_t newState); void sessionResetDone(); void needToSendAsync(); - void sendAnythingAsync(qint64 msWait); + void sendAnythingAsync(int64_t msWait); void sendHttpWaitAsync(); - void sendPongAsync(quint64 msgId, quint64 pingId); - void sendMsgsStateInfoAsync(quint64 msgId, QByteArray data); - void resendAsync(quint64 msgId, qint64 msCanWait, bool forceContainer, bool sendMsgStateInfo); - void resendManyAsync(QVector msgIds, qint64 msCanWait, bool forceContainer, bool sendMsgStateInfo); + void sendPongAsync(uint64_t msgId, uint64_t pingId); + void sendMsgsStateInfoAsync(uint64_t msgId, QByteArray data); + void resendAsync(uint64_t msgId, int64_t msCanWait, bool forceContainer, bool sendMsgStateInfo); + void resendManyAsync(QVector msgIds, int64_t msCanWait, bool forceContainer, bool sendMsgStateInfo); void resendAllAsync(); void finished(internal::Connection *connection); @@ -132,7 +132,7 @@ public slots: void onWaitIPv4Failed(); void onOldConnection(); - void onSentSome(uint64 size); + void onSentSome(uint64_t size); void onReceivedSome(); void onReadyData(); @@ -141,8 +141,8 @@ public slots: void onConnected6(); void onDisconnected4(); void onDisconnected6(); - void onError4(qint32 errorCode); - void onError6(qint32 errorCode); + void onError4(int32_t errorCode); + void onError6(int32_t errorCode); // Auth key creation packet receive slots void pqAnswered(); @@ -184,13 +184,13 @@ private: RestartConnection, ResetSession, }; - HandleResult handleOneReceived(const mtpPrime *from, const mtpPrime *end, uint64 msgId, int32 serverTime, uint64 serverSalt, bool badTime); + HandleResult handleOneReceived(const mtpPrime *from, const mtpPrime *end, uint64_t msgId, int32_t serverTime, uint64_t serverSalt, bool badTime); mtpBuffer ungzip(const mtpPrime *from, const mtpPrime *end) const; void handleMsgsStates(const QVector &ids, const QByteArray &states, QVector &acked); void clearMessages(); - bool setState(int32 state, int32 ifState = Connection::UpdateAlways); + bool setState(int32_t state, int32_t ifState = Connection::UpdateAlways); base::byte_vector encryptPQInnerRSA(const MTPP_Q_inner_data &data, const MTP::internal::RSAPublicKey &key); std::string encryptClientDHInner(const MTPClient_DH_Inner_Data &data); @@ -199,7 +199,7 @@ private: DcType _dcType = DcType::Regular; mutable QReadWriteLock stateConnMutex; - int32 _state = DisconnectedState; + int32_t _state = DisconnectedState; bool _needSessionReset = false; void resetSession(); @@ -212,19 +212,19 @@ private: SingleTimer retryTimer; // exp retry timer int retryTimeout = 1; - qint64 retryWillFinish; + int64_t retryWillFinish; SingleTimer oldConnectionTimer; bool oldConnection = true; SingleTimer _waitForConnectedTimer, _waitForReceivedTimer, _waitForIPv4Timer; - uint32 _waitForReceived, _waitForConnected; + uint32_t _waitForReceived, _waitForConnected; TimeMs firstSentAt = -1; QVector ackRequestData, resendRequestData; // if badTime received - search for ids in sessionData->haveSent and sessionData->wereAcked and sync time/salt, return true if found - bool requestsFixTimeSalt(const QVector &ids, int32 serverTime, uint64 serverSalt); + bool requestsFixTimeSalt(const QVector &ids, int32_t serverTime, uint64_t serverSalt); // remove msgs with such ids from sessionData->haveSent, add to sessionData->wereAcked void requestsAcked(const QVector &ids, bool byResponse = false); @@ -235,8 +235,8 @@ private: mtpMsgId _pingMsgId = 0; SingleTimer _pingSender; - void resend(quint64 msgId, qint64 msCanWait = 0, bool forceContainer = false, bool sendMsgStateInfo = false); - void resendMany(QVector msgIds, qint64 msCanWait = 0, bool forceContainer = false, bool sendMsgStateInfo = false); + void resend(uint64_t msgId, int64_t msCanWait = 0, bool forceContainer = false, bool sendMsgStateInfo = false); + void resendMany(QVector msgIds, int64_t msCanWait = 0, bool forceContainer = false, bool sendMsgStateInfo = false); template void sendRequestNotSecure(const TRequest &request); @@ -247,7 +247,7 @@ private: bool restarted = false; bool _finished = false; - uint64 keyId = 0; + uint64_t keyId = 0; QReadWriteLock sessionDataMutex; SessionData *sessionData = nullptr; @@ -266,17 +266,17 @@ private: MTPint256 &new_nonce; MTPlong &auth_key_aux_hash; - uint32 retries = 0; + uint32_t retries = 0; MTPlong retry_id; - int32 g = 0; + int32_t g = 0; uchar aesKey[32] = { 0 }; uchar aesIV[32] = { 0 }; MTPlong auth_key_hash; - uint32 req_num = 0; // sent not encrypted request number - uint32 msgs_sent = 0; + uint32_t req_num = 0; // sent not encrypted request number + uint32_t msgs_sent = 0; }; struct AuthKeyCreateStrings { std::vector dh_prime; diff --git a/Telegram/SourceFiles/mtproto/connection_abstract.cpp b/Telegram/SourceFiles/mtproto/connection_abstract.cpp index 7b843d7b5..119059384 100644 --- a/Telegram/SourceFiles/mtproto/connection_abstract.cpp +++ b/Telegram/SourceFiles/mtproto/connection_abstract.cpp @@ -33,7 +33,7 @@ AbstractConnection::~AbstractConnection() { mtpBuffer AbstractConnection::preparePQFake(const MTPint128 &nonce) { MTPReq_pq req_pq(nonce); mtpBuffer buffer; - uint32 requestSize = req_pq.innerLength() >> 2; + uint32_t requestSize = req_pq.innerLength() >> 2; buffer.resize(0); buffer.reserve(8 + requestSize); @@ -52,18 +52,18 @@ mtpBuffer AbstractConnection::preparePQFake(const MTPint128 &nonce) { MTPResPQ AbstractConnection::readPQFakeReply(const mtpBuffer &buffer) { const mtpPrime *answer(buffer.constData()); - uint32 len = buffer.size(); + uint32_t len = buffer.size(); if (len < 5) { LOG(("Fake PQ Error: bad request answer, len = %1").arg(len * sizeof(mtpPrime))); DEBUG_LOG(("Fake PQ Error: answer bytes %1").arg(Logs::mb(answer, len * sizeof(mtpPrime)).str())); throw Exception("bad pq reply"); } - if (answer[0] != 0 || answer[1] != 0 || (((uint32)answer[2]) & 0x03) != 1/* || (unixtime() - answer[3] > 300) || (answer[3] - unixtime() > 60)*/) { // didnt sync time yet + if (answer[0] != 0 || answer[1] != 0 || (((uint32_t)answer[2]) & 0x03) != 1/* || (unixtime() - answer[3] > 300) || (answer[3] - unixtime() > 60)*/) { // didnt sync time yet LOG(("Fake PQ Error: bad request answer start (%1 %2 %3)").arg(answer[0]).arg(answer[1]).arg(answer[2])); DEBUG_LOG(("Fake PQ Error: answer bytes %1").arg(Logs::mb(answer, len * sizeof(mtpPrime)).str())); throw Exception("bad pq reply"); } - uint32 answerLen = (uint32)answer[4]; + uint32_t answerLen = (uint32_t)answer[4]; if (answerLen != (len - 5) * sizeof(mtpPrime)) { LOG(("Fake PQ Error: bad request answer %1 <> %2").arg(answerLen).arg((len - 5) * sizeof(mtpPrime))); DEBUG_LOG(("Fake PQ Error: answer bytes %1").arg(Logs::mb(answer, len * sizeof(mtpPrime)).str())); diff --git a/Telegram/SourceFiles/mtproto/connection_abstract.h b/Telegram/SourceFiles/mtproto/connection_abstract.h index ad13427fd..c673d93fd 100644 --- a/Telegram/SourceFiles/mtproto/connection_abstract.h +++ b/Telegram/SourceFiles/mtproto/connection_abstract.h @@ -55,7 +55,7 @@ public: return false; } - virtual int32 debugState() const = 0; + virtual int32_t debugState() const = 0; virtual QString transport() const = 0; @@ -71,7 +71,7 @@ signals: void receivedData(); void receivedSome(); // to stop restart timer - void error(qint32 errorCodebool); + void error(int32_t errorCodebool); void connected(); void disconnected(); diff --git a/Telegram/SourceFiles/mtproto/connection_auto.cpp b/Telegram/SourceFiles/mtproto/connection_auto.cpp index 886cfd9b5..ce07d50c3 100644 --- a/Telegram/SourceFiles/mtproto/connection_auto.cpp +++ b/Telegram/SourceFiles/mtproto/connection_auto.cpp @@ -129,7 +129,7 @@ void AutoConnection::sendData(mtpBuffer &buffer) { } void AutoConnection::httpSend(mtpBuffer &buffer) { - int32 requestSize = (buffer.size() - 3) * sizeof(mtpPrime); + int32_t requestSize = (buffer.size() - 3) * sizeof(mtpPrime); QNetworkRequest request(address); request.setHeader(QNetworkRequest::ContentLengthHeader, QVariant(requestSize)); @@ -250,7 +250,7 @@ void AutoConnection::requestFinished(QNetworkReply *reply) { } } -void AutoConnection::socketPacket(const char *packet, uint32 length) { +void AutoConnection::socketPacket(const char *packet, uint32_t length) { if (status == FinishedWork) return; mtpBuffer data = AbstractTCPConnection::handleResponse(packet, length); @@ -306,7 +306,7 @@ bool AutoConnection::needHttpWait() { return (status == UsingHttp) ? requests.isEmpty() : false; } -int32 AutoConnection::debugState() const { +int32_t AutoConnection::debugState() const { return (status == UsingHttp) ? -1 : ((status == UsingTcp) ? sock.state() : -777); } diff --git a/Telegram/SourceFiles/mtproto/connection_auto.h b/Telegram/SourceFiles/mtproto/connection_auto.h index ff5375f91..7a044b744 100644 --- a/Telegram/SourceFiles/mtproto/connection_auto.h +++ b/Telegram/SourceFiles/mtproto/connection_auto.h @@ -40,7 +40,7 @@ public: bool usingHttpWait() override; bool needHttpWait() override; - int32 debugState() const override; + int32_t debugState() const override; QString transport() const override; @@ -57,7 +57,7 @@ public slots: protected: - void socketPacket(const char *packet, uint32 length) override; + void socketPacket(const char *packet, uint32_t length) override; private: @@ -82,9 +82,9 @@ private: Requests requests; QString _addrTcp, _addrHttp; - int32 _portTcp, _portHttp; + int32_t _portTcp, _portHttp; MTPDdcOption::Flags _flagsTcp, _flagsHttp; - int32 _tcpTimeout; + int32_t _tcpTimeout; QTimer tcpTimeoutTimer; }; diff --git a/Telegram/SourceFiles/mtproto/connection_http.cpp b/Telegram/SourceFiles/mtproto/connection_http.cpp index bab7ee106..44ecdd234 100644 --- a/Telegram/SourceFiles/mtproto/connection_http.cpp +++ b/Telegram/SourceFiles/mtproto/connection_http.cpp @@ -40,8 +40,8 @@ mtpBuffer HTTPConnection::handleResponse(QNetworkReply *reply) { return data; } -qint32 HTTPConnection::handleError(QNetworkReply *reply) { // returnes "maybe bad key" - auto result = qint32(kErrorCodeOther); +int32_t HTTPConnection::handleError(QNetworkReply *reply) { // returnes "maybe bad key" + auto result = int32_t(kErrorCodeOther); QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); if (statusCode.isValid()) { @@ -105,7 +105,7 @@ void HTTPConnection::sendData(mtpBuffer &buffer) { return; } - int32 requestSize = (buffer.size() - 3) * sizeof(mtpPrime); + int32_t requestSize = (buffer.size() - 3) * sizeof(mtpPrime); QNetworkRequest request(address); request.setHeader(QNetworkRequest::ContentLengthHeader, QVariant(requestSize)); @@ -197,7 +197,7 @@ bool HTTPConnection::needHttpWait() { return requests.isEmpty(); } -int32 HTTPConnection::debugState() const { +int32_t HTTPConnection::debugState() const { return -1; } diff --git a/Telegram/SourceFiles/mtproto/connection_http.h b/Telegram/SourceFiles/mtproto/connection_http.h index a3a92971f..d7ac75fbd 100644 --- a/Telegram/SourceFiles/mtproto/connection_http.h +++ b/Telegram/SourceFiles/mtproto/connection_http.h @@ -40,12 +40,12 @@ public: bool usingHttpWait() override; bool needHttpWait() override; - int32 debugState() const override; + int32_t debugState() const override; QString transport() const override; static mtpBuffer handleResponse(QNetworkReply *reply); - static qint32 handleError(QNetworkReply *reply); // returnes error code + static int32_t handleError(QNetworkReply *reply); // returnes error code public slots: void requestFinished(QNetworkReply *reply); diff --git a/Telegram/SourceFiles/mtproto/connection_tcp.cpp b/Telegram/SourceFiles/mtproto/connection_tcp.cpp index 0fbad33cb..5540f0f67 100644 --- a/Telegram/SourceFiles/mtproto/connection_tcp.cpp +++ b/Telegram/SourceFiles/mtproto/connection_tcp.cpp @@ -27,11 +27,11 @@ namespace internal { namespace { -uint32 tcpPacketSize(const char *packet) { // must have at least 4 bytes readable - uint32 result = (packet[0] > 0) ? packet[0] : 0; +uint32_t tcpPacketSize(const char *packet) { // must have at least 4 bytes readable + uint32_t result = (packet[0] > 0) ? packet[0] : 0; if (result == 0x7f) { const uchar *bytes = reinterpret_cast(packet); - result = (((uint32(bytes[3]) << 8) | uint32(bytes[2])) << 8) | uint32(bytes[1]); + result = (((uint32_t(bytes[3]) << 8) | uint32_t(bytes[2])) << 8) | uint32_t(bytes[1]); return (result << 2) + 4; } return (result << 2) + 1; @@ -58,7 +58,7 @@ void AbstractTCPConnection::socketRead() { } do { - uint32 toRead = packetLeft ? packetLeft : (readingToShort ? (MTPShortBufferSize * sizeof(mtpPrime) - packetRead) : 4); + uint32_t toRead = packetLeft ? packetLeft : (readingToShort ? (MTPShortBufferSize * sizeof(mtpPrime) - packetRead) : 4); if (readingToShort) { if (currentPos + toRead > ((char*)shortBuffer) + MTPShortBufferSize * sizeof(mtpPrime)) { longBuffer.resize(((packetRead + toRead) >> 2) + 1); @@ -72,7 +72,7 @@ void AbstractTCPConnection::socketRead() { currentPos = ((char*)&longBuffer[0]) + packetRead; } } - int32 bytes = (int32)sock.read(currentPos, toRead); + int32_t bytes = (int32_t)sock.read(currentPos, toRead); if (bytes > 0) { aesCtrEncrypt(currentPos, bytes, _receiveKey, &_receiveState); TCP_LOG(("TCP Info: read %1 bytes").arg(bytes)); @@ -94,7 +94,7 @@ void AbstractTCPConnection::socketRead() { } else { bool move = false; while (packetRead >= 4) { - uint32 packetSize = tcpPacketSize(currentPos - packetRead); + uint32_t packetSize = tcpPacketSize(currentPos - packetRead); if (packetSize < 5 || packetSize > MTPPacketSizeMax) { LOG(("TCP Error: packet size = %1").arg(packetSize)); emit error(kErrorCodeOther); @@ -136,18 +136,18 @@ void AbstractTCPConnection::socketRead() { } while (sock.state() == QAbstractSocket::ConnectedState && sock.bytesAvailable()); } -mtpBuffer AbstractTCPConnection::handleResponse(const char *packet, uint32 length) { +mtpBuffer AbstractTCPConnection::handleResponse(const char *packet, uint32_t length) { if (length < 5 || length > MTPPacketSizeMax) { LOG(("TCP Error: bad packet size %1").arg(length)); return mtpBuffer(1, -500); } - int32 size = packet[0], len = length - 1; + int32_t size = packet[0], len = length - 1; if (size == 0x7f) { const uchar *bytes = reinterpret_cast(packet); - size = (((uint32(bytes[3]) << 8) | uint32(bytes[2])) << 8) | uint32(bytes[1]); + size = (((uint32_t(bytes[3]) << 8) | uint32_t(bytes[2])) << 8) | uint32_t(bytes[1]); len -= 3; } - if (size * int32(sizeof(mtpPrime)) != len) { + if (size * int32_t(sizeof(mtpPrime)) != len) { LOG(("TCP Error: bad packet header")); TCP_LOG(("TCP Error: bad packet header, packet: %1").arg(Logs::mb(packet, length).str())); return mtpBuffer(1, -500); @@ -277,9 +277,9 @@ void AbstractTCPConnection::tcpSend(mtpBuffer &buffer) { if (!packetNum) { // prepare random part char nonce[64]; - uint32 *first = reinterpret_cast(nonce), *second = first + 1; - uint32 first1 = 0x44414548U, first2 = 0x54534f50U, first3 = 0x20544547U, first4 = 0x20544547U, first5 = 0xeeeeeeeeU; - uint32 second1 = 0; + uint32_t *first = reinterpret_cast(nonce), *second = first + 1; + uint32_t first1 = 0x44414548U, first2 = 0x54534f50U, first3 = 0x20544547U, first4 = 0x20544547U, first5 = 0xeeeeeeeeU; + uint32_t second1 = 0; do { memset_rand(nonce, sizeof(nonce)); } while (*first == first1 || *first == first2 || *first == first3 || *first == first4 || *first == first5 || *second == second1 || *reinterpret_cast(nonce) == 0xef); @@ -297,7 +297,7 @@ void AbstractTCPConnection::tcpSend(mtpBuffer &buffer) { memcpy(_receiveState.ivec, reversed + CTRState::KeySize, CTRState::IvecSize); // write protocol identifier - *reinterpret_cast(nonce + 56) = 0xefefefefU; + *reinterpret_cast(nonce + 56) = 0xefefefefU; sock.write(nonce, 56); aesCtrEncrypt(nonce, 64, _sendKey, &_sendState); @@ -305,7 +305,7 @@ void AbstractTCPConnection::tcpSend(mtpBuffer &buffer) { } ++packetNum; - uint32 size = buffer.size() - 3, len = size * 4; + uint32_t size = buffer.size() - 3, len = size * 4; char *data = reinterpret_cast(&buffer[0]); if (size < 0x7f) { data[7] = char(size); @@ -342,7 +342,7 @@ void TCPConnection::connectTcp(const DcOptions::Endpoint &endpoint) { sock.connectToHost(QHostAddress(_addr), _port); } -void TCPConnection::socketPacket(const char *packet, uint32 length) { +void TCPConnection::socketPacket(const char *packet, uint32_t length) { if (status == FinishedWork) return; mtpBuffer data = handleResponse(packet, length); @@ -372,7 +372,7 @@ bool TCPConnection::isConnected() const { return (status == UsingTcp); } -int32 TCPConnection::debugState() const { +int32_t TCPConnection::debugState() const { return sock.state(); } diff --git a/Telegram/SourceFiles/mtproto/connection_tcp.h b/Telegram/SourceFiles/mtproto/connection_tcp.h index b57175be7..ba9e54988 100644 --- a/Telegram/SourceFiles/mtproto/connection_tcp.h +++ b/Telegram/SourceFiles/mtproto/connection_tcp.h @@ -41,20 +41,20 @@ public slots: protected: QTcpSocket sock; - uint32 packetNum; // sent packet number + uint32_t packetNum; // sent packet number - uint32 packetRead, packetLeft; // reading from socket + uint32_t packetRead, packetLeft; // reading from socket bool readingToShort; char *currentPos; mtpBuffer longBuffer; mtpPrime shortBuffer[MTPShortBufferSize]; - virtual void socketPacket(const char *packet, uint32 length) = 0; + virtual void socketPacket(const char *packet, uint32_t length) = 0; - static mtpBuffer handleResponse(const char *packet, uint32 length); + static mtpBuffer handleResponse(const char *packet, uint32_t length); static void handleError(QAbstractSocket::SocketError e, QTcpSocket &sock); - static uint32 fourCharsToUInt(char ch1, char ch2, char ch3, char ch4) { + static uint32_t fourCharsToUInt(char ch1, char ch2, char ch3, char ch4) { char ch[4] = { ch1, ch2, ch3, ch4 }; - return *reinterpret_cast(ch); + return *reinterpret_cast(ch); } void tcpSend(mtpBuffer &buffer); @@ -79,7 +79,7 @@ public: } bool isConnected() const override; - int32 debugState() const override; + int32_t debugState() const override; QString transport() const override; @@ -94,7 +94,7 @@ public slots: protected: - void socketPacket(const char *packet, uint32 length) override; + void socketPacket(const char *packet, uint32_t length) override; private: @@ -107,7 +107,7 @@ private: MTPint128 tcpNonce; QString _addr; - int32 _port, _tcpTimeout; + int32_t _port, _tcpTimeout; MTPDdcOption::Flags _flags; QTimer tcpTimeoutTimer; diff --git a/Telegram/SourceFiles/mtproto/core_types.cpp b/Telegram/SourceFiles/mtproto/core_types.cpp index 9ae542def..9409acb1c 100644 --- a/Telegram/SourceFiles/mtproto/core_types.cpp +++ b/Telegram/SourceFiles/mtproto/core_types.cpp @@ -22,14 +22,14 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "zlib.h" -uint32 MTPstring::innerLength() const { - uint32 l = v.length(); +uint32_t MTPstring::innerLength() const { + uint32_t l = v.length(); if (l < 254) { l += 1; } else { l += 4; } - uint32 d = l & 0x03; + uint32_t d = l & 0x03; if (d) l += (4 - d); return l; } @@ -38,14 +38,14 @@ void MTPstring::read(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons) if (from + 1 > end) throw mtpErrorInsufficient(); if (cons != mtpc_string) throw mtpErrorUnexpected(cons, "MTPstring"); - uint32 l; + uint32_t l; const uchar *buf = (const uchar*)from; if (buf[0] == 254) { - l = (uint32)buf[1] + ((uint32)buf[2] << 8) + ((uint32)buf[3] << 16); + l = (uint32_t)buf[1] + ((uint32_t)buf[2] << 8) + ((uint32_t)buf[3] << 16); buf += 4; from += ((l + 4) >> 2) + (((l + 4) & 0x03) ? 1 : 0); } else { - l = (uint32)buf[0]; + l = (uint32_t)buf[0]; ++buf; from += ((l + 1) >> 2) + (((l + 1) & 0x03) ? 1 : 0); } @@ -55,7 +55,7 @@ void MTPstring::read(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons) } void MTPstring::write(mtpBuffer &to) const { - uint32 l = v.length(), s = l + ((l < 254) ? 1 : 4), was = to.size(); + uint32_t l = v.length(), s = l + ((l < 254) ? 1 : 4), was = to.size(); if (s & 0x03) { s += 4; } @@ -74,7 +74,7 @@ void MTPstring::write(mtpBuffer &to) const { memcpy(buf, v.constData(), l); } -uint32 mtpRequest::innerLength() const { // for template MTP requests and MTPBoxed instanciation +uint32_t mtpRequest::innerLength() const { // for template MTP requests and MTPBoxed instanciation mtpRequestData *value = data(); if (!value || value->size() < 9) return 0; return value->at(7); @@ -83,7 +83,7 @@ uint32 mtpRequest::innerLength() const { // for template MTP requests and MTPBox void mtpRequest::write(mtpBuffer &to) const { mtpRequestData *value = data(); if (!value || value->size() < 9) return; - uint32 was = to.size(), s = innerLength() / sizeof(mtpPrime); + uint32_t was = to.size(), s = innerLength() / sizeof(mtpPrime); to.resize(was + s); memcpy(to.data() + was, value->constData() + 8, s * sizeof(mtpPrime)); } @@ -113,7 +113,7 @@ bool mtpRequestData::needAckByType(mtpTypeId type) { return true; } -mtpRequest mtpRequestData::prepare(uint32 requestSize, uint32 maxSize) { +mtpRequest mtpRequestData::prepare(uint32_t requestSize, uint32_t maxSize) { if (!maxSize) maxSize = requestSize; mtpRequest result(new mtpRequestData(true)); result->reserve(8 + maxSize + _padding(maxSize)); // 2: salt, 2: session_id, 2: msg_id, 1: seq_no, 1: message_length @@ -125,8 +125,8 @@ mtpRequest mtpRequestData::prepare(uint32 requestSize, uint32 maxSize) { void mtpRequestData::padding(mtpRequest &request) { if (request->size() < 9) return; - uint32 requestSize = (request.innerLength() >> 2), padding = _padding(requestSize), fullSize = 8 + requestSize + padding; // 2: salt, 2: session_id, 2: msg_id, 1: seq_no, 1: message_length - if (uint32(request->size()) != fullSize) { + uint32_t requestSize = (request.innerLength() >> 2), padding = _padding(requestSize), fullSize = 8 + requestSize + padding; // 2: salt, 2: session_id, 2: msg_id, 1: seq_no, 1: message_length + if (uint32_t(request->size()) != fullSize) { request->resize(fullSize); if (padding) { memset_rand(request->data() + (fullSize - padding), padding * sizeof(mtpPrime)); @@ -134,7 +134,7 @@ void mtpRequestData::padding(mtpRequest &request) { } } -uint32 mtpRequestData::_padding(uint32 requestSize) { +uint32_t mtpRequestData::_padding(uint32_t requestSize) { #ifdef TDESKTOP_MTPROTO_OLD return ((8 + requestSize) & 0x03) ? (4 - ((8 + requestSize) & 0x03)) : 0; #else // TDESKTOP_MTPROTO_OLD @@ -149,7 +149,7 @@ uint32 mtpRequestData::_padding(uint32 requestSize) { #endif // TDESKTOP_MTPROTO_OLD } -void mtpTextSerializeCore(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons, uint32 level, mtpPrime vcons) { +void mtpTextSerializeCore(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons, uint32_t level, mtpPrime vcons) { switch (mtpTypeId(cons)) { case mtpc_int: { MTPint value; @@ -199,11 +199,11 @@ void mtpTextSerializeCore(MTPStringLogger &to, const mtpPrime *&from, const mtpP if (from >= end) { throw Exception("from >= end in vector"); } - int32 cnt = *(from++); + int32_t cnt = *(from++); to.add("[ vector<0x").add(QString::number(vcons, 16)).add(">"); if (cnt) { to.add("\n").addSpaces(level); - for (int32 i = 0; i < cnt; ++i) { + for (int32_t i = 0; i < cnt; ++i) { to.add(" "); mtpTextSerializeType(to, from, end, vcons, level + 1); to.add(",\n").addSpaces(level); @@ -217,7 +217,7 @@ void mtpTextSerializeCore(MTPStringLogger &to, const mtpPrime *&from, const mtpP case mtpc_gzip_packed: { MTPstring packed; packed.read(from, end); // read packed string as serialized mtp string type - uint32 packedLen = packed.v.size(), unpackedChunk = packedLen; + uint32_t packedLen = packed.v.size(), unpackedChunk = packedLen; mtpBuffer result; // * 4 because of mtpPrime type result.resize(0); @@ -245,7 +245,7 @@ void mtpTextSerializeCore(MTPStringLogger &to, const mtpPrime *&from, const mtpP } } if (stream.avail_out & 0x03) { - uint32 badSize = result.size() * sizeof(mtpPrime) - stream.avail_out; + uint32_t badSize = result.size() * sizeof(mtpPrime) - stream.avail_out; throw Exception(QString("ungzip bad length, size: %1").arg(badSize)); } result.resize(result.size() - (stream.avail_out >> 2)); @@ -259,7 +259,7 @@ void mtpTextSerializeCore(MTPStringLogger &to, const mtpPrime *&from, const mtpP } break; default: { - for (uint32 i = 1; i < mtpLayerMaxSingle; ++i) { + for (uint32_t i = 1; i < mtpLayerMaxSingle; ++i) { if (cons == mtpLayers[i]) { to.add("[LAYER").add(QString::number(i + 1)).add("] "); mtpTextSerializeType(to, from, end, 0, level); return; @@ -269,7 +269,7 @@ void mtpTextSerializeCore(MTPStringLogger &to, const mtpPrime *&from, const mtpP if (from >= end) { throw Exception("from >= end in invokeWithLayer"); } - int32 layer = *(from++); + int32_t layer = *(from++); to.add("[LAYER").add(QString::number(layer)).add("] "); mtpTextSerializeType(to, from, end, 0, level); return; } diff --git a/Telegram/SourceFiles/mtproto/core_types.h b/Telegram/SourceFiles/mtproto/core_types.h index 59b81db12..b4e505b68 100644 --- a/Telegram/SourceFiles/mtproto/core_types.h +++ b/Telegram/SourceFiles/mtproto/core_types.h @@ -22,23 +22,24 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "core/basic_types.h" #include "base/flags.h" +#include namespace MTP { // type DcId represents actual data center id, while in most cases // we use some shifted ids, like DcId() + X * DCShift -using DcId = int32; -using ShiftedDcId = int32; +using DcId = int32_t; +using ShiftedDcId = int32_t; } // namespace MTP -using mtpPrime = int32; -using mtpRequestId = int32; -using mtpMsgId = uint64; -using mtpPingId = uint64; +using mtpPrime = int32_t; +using mtpRequestId = int32_t; +using mtpMsgId = uint64_t; +using mtpPingId = uint64_t; using mtpBuffer = QVector; -using mtpTypeId = uint32; +using mtpTypeId = uint32_t; class mtpRequestData; class mtpRequest : public QSharedPointer { @@ -47,7 +48,7 @@ public: explicit mtpRequest(mtpRequestData *ptr) : QSharedPointer(ptr) { } - uint32 innerLength() const; + uint32_t innerLength() const; void write(mtpBuffer &to) const; using ResponseType = void; // don't know real response type =( @@ -67,10 +68,10 @@ public: mtpRequestData(bool/* sure*/) { } - static mtpRequest prepare(uint32 requestSize, uint32 maxSize = 0); + static mtpRequest prepare(uint32_t requestSize, uint32_t maxSize = 0); static void padding(mtpRequest &request); - static uint32 messageSize(const mtpRequest &request) { + static uint32_t messageSize(const mtpRequest &request) { if (request->size() < 9) return 0; return 4 + (request.innerLength() >> 2); // 2: msg_id, 1: seq_no, q: message_length } @@ -84,7 +85,7 @@ public: static bool needAckByType(mtpTypeId type); private: - static uint32 _padding(uint32 requestSize); + static uint32_t _padding(uint32_t requestSize); }; @@ -108,7 +109,7 @@ public: class mtpErrorUnexpected : public Exception { public: - mtpErrorUnexpected(mtpTypeId typeId, const QString &type) : Exception(QString("MTP Unexpected type id #%1 read in %2").arg(uint32(typeId), 0, 16).arg(type), false) { // maybe api changed?.. + mtpErrorUnexpected(mtpTypeId typeId, const QString &type) : Exception(QString("MTP Unexpected type id #%1 read in %2").arg(uint32_t(typeId), 0, 16).arg(type), false) { // maybe api changed?.. } }; @@ -275,7 +276,7 @@ static const mtpTypeId mtpLayers[] = { mtpTypeId(mtpc_invokeWithLayer17), mtpTypeId(mtpc_invokeWithLayer18), }; -static const uint32 mtpLayerMaxSingle = sizeof(mtpLayers) / sizeof(mtpLayers[0]); +static const uint32_t mtpLayerMaxSingle = sizeof(mtpLayers) / sizeof(mtpLayers[0]); template class MTPBoxed : public bareT { @@ -291,7 +292,7 @@ public: return *this; } - uint32 innerLength() const { + uint32_t innerLength() const { return sizeof(mtpTypeId) + bareT::innerLength(); } void read(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons = 0) { @@ -314,12 +315,12 @@ class MTPBoxed > { class MTPint { public: - int32 v = 0; + int32_t v = 0; MTPint() = default; - uint32 innerLength() const { - return sizeof(int32); + uint32_t innerLength() const { + return sizeof(int32_t); } mtpTypeId type() const { return mtpc_int; @@ -327,19 +328,19 @@ public: void read(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons = mtpc_int) { if (from + 1 > end) throw mtpErrorInsufficient(); if (cons != mtpc_int) throw mtpErrorUnexpected(cons, "MTPint"); - v = (int32)*(from++); + v = (int32_t)*(from++); } void write(mtpBuffer &to) const { to.push_back((mtpPrime)v); } private: - explicit MTPint(int32 val) : v(val) { + explicit MTPint(int32_t val) : v(val) { } - friend MTPint MTP_int(int32 v); + friend MTPint MTP_int(int32_t v); }; -inline MTPint MTP_int(int32 v) { +inline MTPint MTP_int(int32_t v) { return MTPint(v); } using MTPInt = MTPBoxed; @@ -355,13 +356,13 @@ template class MTPflags { public: Flags v = 0; - static_assert(sizeof(Flags) == sizeof(int32), "MTPflags are allowed only wrapping int32 flag types!"); + static_assert(sizeof(Flags) == sizeof(int32_t), "MTPflags are allowed only wrapping int32_t flag types!"); MTPflags() = default; MTPflags(internal::ZeroFlagsHelper helper) { } - uint32 innerLength() const { + uint32_t innerLength() const { return sizeof(Flags); } mtpTypeId type() const { @@ -414,12 +415,12 @@ inline bool operator!=(const MTPint &a, const MTPint &b) { class MTPlong { public: - uint64 v = 0; + uint64_t v = 0; MTPlong() = default; - uint32 innerLength() const { - return sizeof(uint64); + uint32_t innerLength() const { + return sizeof(uint64_t); } mtpTypeId type() const { return mtpc_long; @@ -427,7 +428,7 @@ public: void read(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons = mtpc_long) { if (from + 2 > end) throw mtpErrorInsufficient(); if (cons != mtpc_long) throw mtpErrorUnexpected(cons, "MTPlong"); - v = (uint64)(((uint32*)from)[0]) | ((uint64)(((uint32*)from)[1]) << 32); + v = (uint64_t)(((uint32_t*)from)[0]) | ((uint64_t)(((uint32_t*)from)[1]) << 32); from += 2; } void write(mtpBuffer &to) const { @@ -436,12 +437,12 @@ public: } private: - explicit MTPlong(uint64 val) : v(val) { + explicit MTPlong(uint64_t val) : v(val) { } - friend MTPlong MTP_long(uint64 v); + friend MTPlong MTP_long(uint64_t v); }; -inline MTPlong MTP_long(uint64 v) { +inline MTPlong MTP_long(uint64_t v) { return MTPlong(v); } using MTPLong = MTPBoxed; @@ -455,13 +456,13 @@ inline bool operator!=(const MTPlong &a, const MTPlong &b) { class MTPint128 { public: - uint64 l = 0; - uint64 h = 0; + uint64_t l = 0; + uint64_t h = 0; MTPint128() = default; - uint32 innerLength() const { - return sizeof(uint64) + sizeof(uint64); + uint32_t innerLength() const { + return sizeof(uint64_t) + sizeof(uint64_t); } mtpTypeId type() const { return mtpc_int128; @@ -469,8 +470,8 @@ public: void read(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons = mtpc_int128) { if (from + 4 > end) throw mtpErrorInsufficient(); if (cons != mtpc_int128) throw mtpErrorUnexpected(cons, "MTPint128"); - l = (uint64)(((uint32*)from)[0]) | ((uint64)(((uint32*)from)[1]) << 32); - h = (uint64)(((uint32*)from)[2]) | ((uint64)(((uint32*)from)[3]) << 32); + l = (uint64_t)(((uint32_t*)from)[0]) | ((uint64_t)(((uint32_t*)from)[1]) << 32); + h = (uint64_t)(((uint32_t*)from)[2]) | ((uint64_t)(((uint32_t*)from)[3]) << 32); from += 4; } void write(mtpBuffer &to) const { @@ -481,12 +482,12 @@ public: } private: - explicit MTPint128(uint64 low, uint64 high) : l(low), h(high) { + explicit MTPint128(uint64_t low, uint64_t high) : l(low), h(high) { } - friend MTPint128 MTP_int128(uint64 l, uint64 h); + friend MTPint128 MTP_int128(uint64_t l, uint64_t h); }; -inline MTPint128 MTP_int128(uint64 l, uint64 h) { +inline MTPint128 MTP_int128(uint64_t l, uint64_t h) { return MTPint128(l, h); } using MTPInt128 = MTPBoxed; @@ -505,7 +506,7 @@ public: MTPint256() = default; - uint32 innerLength() const { + uint32_t innerLength() const { return l.innerLength() + h.innerLength(); } mtpTypeId type() const { @@ -541,12 +542,12 @@ inline bool operator!=(const MTPint256 &a, const MTPint256 &b) { class MTPdouble { public: - float64 v = 0.; + double v = 0.; MTPdouble() = default; - uint32 innerLength() const { - return sizeof(float64); + uint32_t innerLength() const { + return sizeof(double); } mtpTypeId type() const { return mtpc_double; @@ -554,22 +555,22 @@ public: void read(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons = mtpc_double) { if (from + 2 > end) throw mtpErrorInsufficient(); if (cons != mtpc_double) throw mtpErrorUnexpected(cons, "MTPdouble"); - *(uint64*)(&v) = (uint64)(((uint32*)from)[0]) | ((uint64)(((uint32*)from)[1]) << 32); + *(uint64_t*)(&v) = (uint64_t)(((uint32_t*)from)[0]) | ((uint64_t)(((uint32_t*)from)[1]) << 32); from += 2; } void write(mtpBuffer &to) const { - uint64 iv = *(uint64*)(&v); + uint64_t iv = *(uint64_t*)(&v); to.push_back((mtpPrime)(iv & 0xFFFFFFFFL)); to.push_back((mtpPrime)(iv >> 32)); } private: - explicit MTPdouble(float64 val) : v(val) { + explicit MTPdouble(double val) : v(val) { } - friend MTPdouble MTP_double(float64 v); + friend MTPdouble MTP_double(double v); }; -inline MTPdouble MTP_double(float64 v) { +inline MTPdouble MTP_double(double v) { return MTPdouble(v); } using MTPDouble = MTPBoxed; @@ -588,7 +589,7 @@ class MTPstring { public: MTPstring() = default; - uint32 innerLength() const; + uint32_t innerLength() const; mtpTypeId type() const { return mtpc_string; } @@ -669,8 +670,8 @@ class MTPvector { public: MTPvector() = default; - uint32 innerLength() const { - uint32 result(sizeof(uint32)); + uint32_t innerLength() const { + uint32_t result(sizeof(uint32_t)); for_const (auto &item, v) { result += item.innerLength(); } @@ -682,7 +683,7 @@ public: void read(const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons = mtpc_vector) { if (from + 1 > end) throw mtpErrorInsufficient(); if (cons != mtpc_vector) throw mtpErrorUnexpected(cons, "MTPvector"); - auto count = static_cast(*(from++)); + auto count = static_cast(*(from++)); auto vector = QVector(count, T()); for (auto &item : vector) { @@ -704,9 +705,9 @@ private: } template - friend MTPvector MTP_vector(uint32 count); + friend MTPvector MTP_vector(uint32_t count); template - friend MTPvector MTP_vector(uint32 count, const U &value); + friend MTPvector MTP_vector(uint32_t count, const U &value); template friend MTPvector MTP_vector(const QVector &v); template @@ -714,11 +715,11 @@ private: }; template -inline MTPvector MTP_vector(uint32 count) { +inline MTPvector MTP_vector(uint32_t count) { return MTPvector(QVector(count)); } template -inline MTPvector MTP_vector(uint32 count, const T &value) { +inline MTPvector MTP_vector(uint32_t count, const T &value) { return MTPvector(QVector(count, value)); } template @@ -755,7 +756,7 @@ struct MTPStringLogger { return add(d.constData(), d.size()); } - MTPStringLogger &add(const char *data, int32 len = -1) { + MTPStringLogger &add(const char *data, int32_t len = -1) { if (len < 0) len = strlen(data); if (!len) return (*this); @@ -765,8 +766,8 @@ struct MTPStringLogger { return (*this); } - MTPStringLogger &addSpaces(int32 level) { - int32 len = level * 2; + MTPStringLogger &addSpaces(int32_t level) { + int32_t len = level * 2; if (!len) return (*this); ensureLength(len); @@ -777,10 +778,10 @@ struct MTPStringLogger { return (*this); } - void ensureLength(int32 add) { + void ensureLength(int32_t add) { if (size + add <= alloced) return; - int32 newsize = size + add; + int32_t newsize = size + add; if (newsize % MTPDebugBufferSize) newsize += MTPDebugBufferSize - (newsize % MTPDebugBufferSize); char *b = new char[newsize]; memcpy(b, p, size); @@ -789,12 +790,12 @@ struct MTPStringLogger { p = b; } char *p; - int32 size, alloced; + int32_t size, alloced; }; -void mtpTextSerializeType(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpPrime cons = 0, uint32 level = 0, mtpPrime vcons = 0); +void mtpTextSerializeType(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpPrime cons = 0, uint32_t level = 0, mtpPrime vcons = 0); -void mtpTextSerializeCore(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons, uint32 level, mtpPrime vcons = 0); +void mtpTextSerializeCore(MTPStringLogger &to, const mtpPrime *&from, const mtpPrime *end, mtpTypeId cons, uint32_t level, mtpPrime vcons = 0); inline QString mtpTextSerialize(const mtpPrime *&from, const mtpPrime *end) { MTPStringLogger to; diff --git a/Telegram/SourceFiles/mtproto/dc_options.cpp b/Telegram/SourceFiles/mtproto/dc_options.cpp index b872cc7d9..bb5bf5385 100644 --- a/Telegram/SourceFiles/mtproto/dc_options.cpp +++ b/Telegram/SourceFiles/mtproto/dc_options.cpp @@ -217,13 +217,13 @@ QByteArray DcOptions::serialize() const { ReadLocker lock(this); - auto size = sizeof(qint32); + auto size = sizeof(int32_t); for (auto &item : _data) { if (isTemporaryDcId(item.first)) { continue; } - size += sizeof(qint32) + sizeof(qint32) + sizeof(qint32); // id + flags + port - size += sizeof(qint32) + item.second.ip.size(); + size += sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t); // id + flags + port + size += sizeof(int32_t) + item.second.ip.size(); } auto count = 0; @@ -240,7 +240,7 @@ QByteArray DcOptions::serialize() const { for (auto &keysInDc : _cdnPublicKeys) { for (auto &entry : keysInDc.second) { publicKeys.push_back({ keysInDc.first, entry.second.getN(), entry.second.getE() }); - size += sizeof(qint32) + Serialize::bytesSize(publicKeys.back().n) + Serialize::bytesSize(publicKeys.back().e); + size += sizeof(int32_t) + Serialize::bytesSize(publicKeys.back().n) + Serialize::bytesSize(publicKeys.back().e); } } @@ -249,18 +249,18 @@ QByteArray DcOptions::serialize() const { { QDataStream stream(&result, QIODevice::WriteOnly); stream.setVersion(QDataStream::Qt_5_1); - stream << qint32(_data.size()); + stream << int32_t(_data.size()); for (auto &item : _data) { if (isTemporaryDcId(item.first)) { continue; } - stream << qint32(item.second.id) << qint32(item.second.flags) << qint32(item.second.port); - stream << qint32(item.second.ip.size()); + stream << int32_t(item.second.id) << int32_t(item.second.flags) << int32_t(item.second.port); + stream << int32_t(item.second.ip.size()); stream.writeRawData(item.second.ip.data(), item.second.ip.size()); } - stream << qint32(publicKeys.size()); + stream << int32_t(publicKeys.size()); for (auto &key : publicKeys) { - stream << qint32(key.dcId) << Serialize::bytes(key.n) << Serialize::bytes(key.e); + stream << int32_t(key.dcId) << Serialize::bytes(key.n) << Serialize::bytes(key.e); } } return result; @@ -269,7 +269,7 @@ QByteArray DcOptions::serialize() const { void DcOptions::constructFromSerialized(const QByteArray &serialized) { QDataStream stream(serialized); stream.setVersion(QDataStream::Qt_5_1); - auto count = qint32(0); + auto count = int32_t(0); stream >> count; if (stream.status() != QDataStream::Ok) { LOG(("MTP Error: Bad data for DcOptions::constructFromSerialized()")); @@ -279,7 +279,7 @@ void DcOptions::constructFromSerialized(const QByteArray &serialized) { WriteLocker lock(this); _data.clear(); for (auto i = 0; i != count; ++i) { - qint32 id = 0, flags = 0, port = 0, ipSize = 0; + int32_t id = 0, flags = 0, port = 0, ipSize = 0; stream >> id >> flags >> port >> ipSize; // https://stackoverflow.com/questions/1076714/max-length-for-client-ip-address @@ -302,7 +302,7 @@ void DcOptions::constructFromSerialized(const QByteArray &serialized) { // Read CDN config if (!stream.atEnd()) { - auto count = qint32(0); + auto count = int32_t(0); stream >> count; if (stream.status() != QDataStream::Ok) { LOG(("MTP Error: Bad data for CDN config in DcOptions::constructFromSerialized()")); @@ -310,7 +310,7 @@ void DcOptions::constructFromSerialized(const QByteArray &serialized) { } for (auto i = 0; i != count; ++i) { - qint32 dcId = 0; + int32_t dcId = 0; base::byte_vector n, e; stream >> dcId >> Serialize::bytes(n) >> Serialize::bytes(e); if (stream.status() != QDataStream::Ok) { @@ -382,9 +382,9 @@ bool DcOptions::hasCDNKeysForDc(DcId dcId) const { } bool DcOptions::getDcRSAKey(DcId dcId, const QVector &fingerprints, internal::RSAPublicKey *result) const { - auto findKey = [&fingerprints, &result](const std::map &keys) { + auto findKey = [&fingerprints, &result](const std::map &keys) { for_const (auto &fingerprint, fingerprints) { - auto it = keys.find(static_cast(fingerprint.v)); + auto it = keys.find(static_cast(fingerprint.v)); if (it != keys.cend()) { *result = it->second; return true; diff --git a/Telegram/SourceFiles/mtproto/dc_options.h b/Telegram/SourceFiles/mtproto/dc_options.h index 6a2fd55c9..894c2b78b 100644 --- a/Telegram/SourceFiles/mtproto/dc_options.h +++ b/Telegram/SourceFiles/mtproto/dc_options.h @@ -106,8 +106,8 @@ private: std::map _data; std::set _cdnDcIds; - std::map _publicKeys; - std::map> _cdnPublicKeys; + std::map _publicKeys; + std::map> _cdnPublicKeys; mutable QReadWriteLock _useThroughLockers; mutable base::Observable _changed; diff --git a/Telegram/SourceFiles/mtproto/facade.h b/Telegram/SourceFiles/mtproto/facade.h index 85bfdb4af..b0e6297f6 100644 --- a/Telegram/SourceFiles/mtproto/facade.h +++ b/Telegram/SourceFiles/mtproto/facade.h @@ -178,7 +178,7 @@ inline DcId maindc() { return MainInstance()->mainDcId(); } -inline int32 dcstate(ShiftedDcId shiftedDcId = 0) { +inline int32_t dcstate(ShiftedDcId shiftedDcId = 0) { if (auto instance = MainInstance()) { return instance->dcstate(shiftedDcId); } @@ -222,7 +222,7 @@ inline void stopSession(ShiftedDcId shiftedDcId) { return MainInstance()->stopSession(shiftedDcId); } -inline int32 state(mtpRequestId requestId) { // < 0 means waiting for such count of ms +inline int32_t state(mtpRequestId requestId) { // < 0 means waiting for such count of ms return MainInstance()->state(requestId); } @@ -232,7 +232,7 @@ template mtpRequestId Session::send(const TRequest &request, RPCResponseHandler callbacks, TimeMs msCanWait, bool needsLayer, bool toMainDC, mtpRequestId after) { mtpRequestId requestId = 0; try { - uint32 requestSize = request.innerLength() >> 2; + uint32_t requestSize = request.innerLength() >> 2; mtpRequest reqSerialized(mtpRequestData::prepare(requestSize)); request.write(*reqSerialized); diff --git a/Telegram/SourceFiles/mtproto/mtp_instance.cpp b/Telegram/SourceFiles/mtproto/mtp_instance.cpp index 255de3cd2..c406dcd2b 100644 --- a/Telegram/SourceFiles/mtproto/mtp_instance.cpp +++ b/Telegram/SourceFiles/mtproto/mtp_instance.cpp @@ -57,11 +57,11 @@ public: void restart(); void restart(ShiftedDcId shiftedDcId); - int32 dcstate(ShiftedDcId shiftedDcId = 0); + int32_t dcstate(ShiftedDcId shiftedDcId = 0); QString dctransport(ShiftedDcId shiftedDcId = 0); void ping(); void cancel(mtpRequestId requestId); - int32 state(mtpRequestId requestId); // < 0 means waiting for such count of ms + int32_t state(mtpRequestId requestId); // < 0 means waiting for such count of ms void killSession(ShiftedDcId shiftedDcId); void killSession(std::unique_ptr session); void stopSession(ShiftedDcId shiftedDcId); @@ -74,18 +74,18 @@ public: void queueQuittingConnection(std::unique_ptr connection); void connectionFinished(internal::Connection *connection); - void registerRequest(mtpRequestId requestId, int32 dcWithShift); + void registerRequest(mtpRequestId requestId, int32_t dcWithShift); void unregisterRequest(mtpRequestId requestId); mtpRequestId storeRequest(mtpRequest &request, const RPCResponseHandler &parser); mtpRequest getRequest(mtpRequestId requestId); - void clearCallbacks(mtpRequestId requestId, int32 errorCode = RPCError::NoError); // 0 - do not toggle onError callback + void clearCallbacks(mtpRequestId requestId, int32_t errorCode = RPCError::NoError); // 0 - do not toggle onError callback void clearCallbacksDelayed(const RPCCallbackClears &requestIds); void performDelayedClear(); void execCallback(mtpRequestId requestId, const mtpPrime *from, const mtpPrime *end); bool hasCallbacks(mtpRequestId requestId); void globalCallback(const mtpPrime *from, const mtpPrime *end); - void onStateChange(ShiftedDcId dcWithShift, int32 state); + void onStateChange(ShiftedDcId dcWithShift, int32_t state); void onSessionReset(ShiftedDcId dcWithShift); // return true if need to clean request data @@ -96,7 +96,7 @@ public: void setUpdatesHandler(RPCDoneHandlerPtr onDone); void setGlobalFailHandler(RPCFailHandlerPtr onFail); - void setStateChangedHandler(base::lambda handler); + void setStateChangedHandler(base::lambda handler); void setSessionResetHandler(base::lambda handler); void clearGlobalHandlers(); @@ -184,7 +184,7 @@ private: RPCCallbackClears _toClear; RPCResponseHandler _globalHandler; - base::lambda _stateChangedHandler; + base::lambda _stateChangedHandler; base::lambda _sessionResetHandler; base::Timer _checkDelayedTimer; @@ -202,7 +202,7 @@ Instance::Private::Private(not_null instance, not_null op void Instance::Private::start(Config &&config) { if (isKeysDestroyer()) { - _instance->connect(_instance, SIGNAL(keyDestroyed(qint32)), _instance, SLOT(onKeyDestroyed(qint32)), Qt::QueuedConnection); + _instance->connect(_instance, SIGNAL(keyDestroyed(int32_t)), _instance, SLOT(onKeyDestroyed(int32_t)), Qt::QueuedConnection); } else if (isNormal()) { unixtimeInit(); } @@ -322,7 +322,7 @@ void Instance::Private::restart(ShiftedDcId shiftedDcId) { } } -int32 Instance::Private::dcstate(ShiftedDcId shiftedDcId) { +int32_t Instance::Private::dcstate(ShiftedDcId shiftedDcId) { if (!shiftedDcId) { Assert(_mainSession != nullptr); return _mainSession->getState(); @@ -391,7 +391,7 @@ void Instance::Private::cancel(mtpRequestId requestId) { clearCallbacks(requestId); } -int32 Instance::Private::state(mtpRequestId requestId) { // < 0 means waiting for such count of ms +int32_t Instance::Private::state(mtpRequestId requestId) { // < 0 means waiting for such count of ms if (requestId > 0) { QMutexLocker locker(&_requestByDcLock); auto i = _requestsByDc.find(requestId); @@ -669,7 +669,7 @@ void Instance::Private::checkDelayedRequests() { } } -void Instance::Private::registerRequest(mtpRequestId requestId, int32 dcWithShift) { +void Instance::Private::registerRequest(mtpRequestId requestId, int32_t dcWithShift) { { QMutexLocker locker(&_requestByDcLock); _requestsByDc.emplace(requestId, dcWithShift); @@ -716,7 +716,7 @@ mtpRequest Instance::Private::getRequest(mtpRequestId requestId) { } -void Instance::Private::clearCallbacks(mtpRequestId requestId, int32 errorCode) { +void Instance::Private::clearCallbacks(mtpRequestId requestId, int32_t errorCode) { RPCResponseHandler h; bool found = false; { @@ -735,19 +735,19 @@ void Instance::Private::clearCallbacks(mtpRequestId requestId, int32 errorCode) } void Instance::Private::clearCallbacksDelayed(const RPCCallbackClears &requestIds) { - uint32 idsCount = requestIds.size(); + uint32_t idsCount = requestIds.size(); if (!idsCount) return; if (cDebug()) { QString idsStr = QString("%1").arg(requestIds[0].requestId); - for (uint32 i = 1; i < idsCount; ++i) { + for (uint32_t i = 1; i < idsCount; ++i) { idsStr += QString(", %1").arg(requestIds[i].requestId); } DEBUG_LOG(("RPC Info: clear callbacks delayed, msgIds: %1").arg(idsStr)); } QMutexLocker lock(&_toClearLock); - uint32 toClearNow = _toClear.size(); + uint32_t toClearNow = _toClear.size(); if (toClearNow) { _toClear.resize(toClearNow + idsCount); memcpy(_toClear.data() + toClearNow, requestIds.constData(), idsCount * sizeof(RPCCallbackClear)); @@ -829,13 +829,13 @@ void Instance::Private::globalCallback(const mtpPrime *from, const mtpPrime *end } } -void Instance::Private::onStateChange(int32 dcWithShift, int32 state) { +void Instance::Private::onStateChange(int32_t dcWithShift, int32_t state) { if (_stateChangedHandler) { _stateChangedHandler(dcWithShift, state); } } -void Instance::Private::onSessionReset(int32 dcWithShift) { +void Instance::Private::onSessionReset(int32_t dcWithShift) { if (_sessionResetHandler) { _sessionResetHandler(dcWithShift); } @@ -1016,7 +1016,7 @@ bool Instance::Private::onErrorDefault(mtpRequestId requestId, const RPCError &e } else if (code < 0 || code >= 500 || (m = QRegularExpression("^FLOOD_WAIT_(\\d+)$").match(err)).hasMatch()) { if (!requestId) return false; - int32 secs = 1; + int32_t secs = 1; if (code < 0 || code >= 500) { auto it = _requestsDelays.find(requestId); if (it != _requestsDelays.cend()) { @@ -1243,7 +1243,7 @@ void Instance::Private::setGlobalFailHandler(RPCFailHandlerPtr onFail) { _globalHandler.onFail = onFail; } -void Instance::Private::setStateChangedHandler(base::lambda handler) { +void Instance::Private::setStateChangedHandler(base::lambda handler) { _stateChangedHandler = std::move(handler); } @@ -1254,7 +1254,7 @@ void Instance::Private::setSessionResetHandler(base::lambda()); + setStateChangedHandler(base::lambda()); setSessionResetHandler(base::lambda()); } @@ -1317,7 +1317,7 @@ void Instance::restart(ShiftedDcId shiftedDcId) { _private->restart(shiftedDcId); } -int32 Instance::dcstate(ShiftedDcId shiftedDcId) { +int32_t Instance::dcstate(ShiftedDcId shiftedDcId) { return _private->dcstate(shiftedDcId); } @@ -1333,7 +1333,7 @@ void Instance::cancel(mtpRequestId requestId) { _private->cancel(requestId); } -int32 Instance::state(mtpRequestId requestId) { // < 0 means waiting for such count of ms +int32_t Instance::state(mtpRequestId requestId) { // < 0 means waiting for such count of ms return _private->state(requestId); } @@ -1389,7 +1389,7 @@ void Instance::setGlobalFailHandler(RPCFailHandlerPtr onFail) { _private->setGlobalFailHandler(onFail); } -void Instance::setStateChangedHandler(base::lambda handler) { +void Instance::setStateChangedHandler(base::lambda handler) { _private->setStateChangedHandler(std::move(handler)); } @@ -1401,7 +1401,7 @@ void Instance::clearGlobalHandlers() { _private->clearGlobalHandlers(); } -void Instance::onStateChange(ShiftedDcId dcWithShift, int32 state) { +void Instance::onStateChange(ShiftedDcId dcWithShift, int32_t state) { _private->onStateChange(dcWithShift, state); } @@ -1453,7 +1453,7 @@ void Instance::scheduleKeyDestroy(ShiftedDcId shiftedDcId) { _private->scheduleKeyDestroy(shiftedDcId); } -void Instance::onKeyDestroyed(qint32 shiftedDcId) { +void Instance::onKeyDestroyed(int32_t shiftedDcId) { _private->completedKeyDestroy(shiftedDcId); } diff --git a/Telegram/SourceFiles/mtproto/mtp_instance.h b/Telegram/SourceFiles/mtproto/mtp_instance.h index 32d65d115..fb1101587 100644 --- a/Telegram/SourceFiles/mtproto/mtp_instance.h +++ b/Telegram/SourceFiles/mtproto/mtp_instance.h @@ -78,7 +78,7 @@ public: } template - mtpRequestId send(const TRequest &request, RPCDoneHandlerPtr onDone, RPCFailHandlerPtr onFail = RPCFailHandlerPtr(), int32 dc = 0, TimeMs msCanWait = 0, mtpRequestId after = 0) { + mtpRequestId send(const TRequest &request, RPCDoneHandlerPtr onDone, RPCFailHandlerPtr onFail = RPCFailHandlerPtr(), int32_t dc = 0, TimeMs msCanWait = 0, mtpRequestId after = 0) { return send(request, RPCResponseHandler(onDone, onFail), dc, msCanWait, after); } @@ -90,11 +90,11 @@ public: void restart(); void restart(ShiftedDcId shiftedDcId); - int32 dcstate(ShiftedDcId shiftedDcId = 0); + int32_t dcstate(ShiftedDcId shiftedDcId = 0); QString dctransport(ShiftedDcId shiftedDcId = 0); void ping(); void cancel(mtpRequestId requestId); - int32 state(mtpRequestId requestId); // < 0 means waiting for such count of ms + int32_t state(mtpRequestId requestId); // < 0 means waiting for such count of ms void killSession(ShiftedDcId shiftedDcId); void stopSession(ShiftedDcId shiftedDcId); void reInitConnection(DcId dcId); @@ -107,11 +107,11 @@ public: void setUpdatesHandler(RPCDoneHandlerPtr onDone); void setGlobalFailHandler(RPCFailHandlerPtr onFail); - void setStateChangedHandler(base::lambda handler); + void setStateChangedHandler(base::lambda handler); void setSessionResetHandler(base::lambda handler); void clearGlobalHandlers(); - void onStateChange(ShiftedDcId dcWithShift, int32 state); + void onStateChange(ShiftedDcId dcWithShift, int32_t state); void onSessionReset(ShiftedDcId dcWithShift); void registerRequest(mtpRequestId requestId, ShiftedDcId dcWithShift); @@ -140,11 +140,11 @@ public slots: signals: void configLoaded(); void cdnConfigLoaded(); - void keyDestroyed(qint32 shiftedDcId); + void keyDestroyed(int32_t shiftedDcId); void allKeysDestroyed(); private slots: - void onKeyDestroyed(qint32 shiftedDcId); + void onKeyDestroyed(int32_t shiftedDcId); private: internal::Session *getSession(ShiftedDcId shiftedDcId); diff --git a/Telegram/SourceFiles/mtproto/rpc_sender.h b/Telegram/SourceFiles/mtproto/rpc_sender.h index aa914baa1..2c9799325 100644 --- a/Telegram/SourceFiles/mtproto/rpc_sender.h +++ b/Telegram/SourceFiles/mtproto/rpc_sender.h @@ -39,7 +39,7 @@ public: } } - int32 code() const { + int32_t code() const { return _code; } @@ -58,7 +58,7 @@ public: private: - int32 _code; + int32_t _code; QString _type, _description; }; @@ -271,11 +271,11 @@ private: }; struct RPCCallbackClear { - RPCCallbackClear(mtpRequestId id = 0, int32 code = RPCError::NoError) : requestId(id), errorCode(code) { + RPCCallbackClear(mtpRequestId id = 0, int32_t code = RPCError::NoError) : requestId(id), errorCode(code) { } mtpRequestId requestId; - int32 errorCode; + int32_t errorCode; }; @@ -847,8 +847,8 @@ protected: }; -using MTPStateChangedHandler = void (*)(int32 dcId, int32 state); -using MTPSessionResetHandler = void (*)(int32 dcId); +using MTPStateChangedHandler = void (*)(int32_t dcId, int32_t state); +using MTPSessionResetHandler = void (*)(int32_t dcId); template class RPCHandlerImplementation : public Base { diff --git a/Telegram/SourceFiles/mtproto/rsa_public_key.cpp b/Telegram/SourceFiles/mtproto/rsa_public_key.cpp index 4a088cf7a..a9b09956f 100644 --- a/Telegram/SourceFiles/mtproto/rsa_public_key.cpp +++ b/Telegram/SourceFiles/mtproto/rsa_public_key.cpp @@ -57,7 +57,7 @@ public: Expects(isValid()); return toBytes(_rsa->e); } - uint64 getFingerPrint() const { + uint64_t getFingerPrint() const { return _fingerprint; } bool isValid() const { @@ -110,7 +110,7 @@ private: MTP_bytes(toBytes(_rsa->e)).write(string); uchar sha1Buffer[20]; - _fingerprint = *(uint64*)(hashSha1(&string[0], string.size() * sizeof(mtpPrime), sha1Buffer) + 3); + _fingerprint = *(uint64_t*)(hashSha1(&string[0], string.size() * sizeof(mtpPrime), sha1Buffer) + 3); } static base::byte_vector toBytes(BIGNUM *number) { auto size = BN_num_bytes(number); @@ -120,7 +120,7 @@ private: } RSA *_rsa = nullptr; - uint64 _fingerprint = 0; + uint64_t _fingerprint = 0; }; @@ -134,7 +134,7 @@ bool RSAPublicKey::isValid() const { return _private && _private->isValid(); } -uint64 RSAPublicKey::getFingerPrint() const { +uint64_t RSAPublicKey::getFingerPrint() const { Expects(isValid()); return _private->getFingerPrint(); } diff --git a/Telegram/SourceFiles/mtproto/rsa_public_key.h b/Telegram/SourceFiles/mtproto/rsa_public_key.h index 16beb8b2d..03eb0213e 100644 --- a/Telegram/SourceFiles/mtproto/rsa_public_key.h +++ b/Telegram/SourceFiles/mtproto/rsa_public_key.h @@ -36,7 +36,7 @@ public: RSAPublicKey &operator=(const RSAPublicKey &other) = default; bool isValid() const; - uint64 getFingerPrint() const; + uint64_t getFingerPrint() const; base::byte_vector getN() const; base::byte_vector getE() const; diff --git a/Telegram/SourceFiles/mtproto/session.cpp b/Telegram/SourceFiles/mtproto/session.cpp index cfe111134..b683fc4e3 100644 --- a/Telegram/SourceFiles/mtproto/session.cpp +++ b/Telegram/SourceFiles/mtproto/session.cpp @@ -29,7 +29,7 @@ namespace internal { void SessionData::setKey(const AuthKeyPtr &key) { if (_authKey != key) { - uint64 session = rand_value(); + uint64_t session = rand_value(); _authKey = key; DEBUG_LOG(("MTP Info: new auth key set in SessionData, id %1, setting random server_session %2").arg(key ? key->keyId() : 0).arg(session)); @@ -175,7 +175,7 @@ void Session::unpaused() { } } -void Session::sendAnything(qint64 msCanWait) { +void Session::sendAnything(int64_t msCanWait) { if (_killed) { DEBUG_LOG(("Session Error: can't send anything in a killed session")); return; @@ -224,11 +224,11 @@ void Session::needToResumeAndSend() { } } -void Session::sendPong(quint64 msgId, quint64 pingId) { +void Session::sendPong(uint64_t msgId, uint64_t pingId) { send(MTP_pong(MTP_long(msgId), MTP_long(pingId))); } -void Session::sendMsgsStateInfo(quint64 msgId, QByteArray data) { +void Session::sendMsgsStateInfo(uint64_t msgId, QByteArray data) { auto info = std::string(); if (!data.isEmpty()) { info.resize(data.size()); @@ -248,7 +248,7 @@ void Session::checkRequestsByTimer() { { QReadLocker locker(data.haveSentMutex()); mtpRequestMap &haveSent(data.haveSentMap()); - uint32 haveSentCount(haveSent.size()); + uint32_t haveSentCount(haveSent.size()); auto ms = getms(true); for (mtpRequestMap::iterator i = haveSent.begin(), e = haveSent.end(); i != e; ++i) { mtpRequest &req(i.value()); @@ -263,7 +263,7 @@ void Session::checkRequestsByTimer() { stateRequestIds.push_back(i.key()); } } - } else if (unixtime() > (int32)(i.key() >> 32) + MTPContainerLives) { + } else if (unixtime() > (int32_t)(i.key() >> 32) + MTPContainerLives) { removingIds.reserve(haveSentCount); removingIds.push_back(i.key()); } @@ -274,14 +274,14 @@ void Session::checkRequestsByTimer() { DEBUG_LOG(("MTP Info: requesting state of msgs: %1").arg(Logs::vector(stateRequestIds))); { QWriteLocker locker(data.stateRequestMutex()); - for (uint32 i = 0, l = stateRequestIds.size(); i < l; ++i) { + for (uint32_t i = 0, l = stateRequestIds.size(); i < l; ++i) { data.stateRequestMap().insert(stateRequestIds[i], true); } } sendAnything(MTPCheckResendWaiting); } if (!resendingIds.isEmpty()) { - for (uint32 i = 0, l = resendingIds.size(); i < l; ++i) { + for (uint32_t i = 0, l = resendingIds.size(); i < l; ++i) { DEBUG_LOG(("MTP Info: resending request %1").arg(resendingIds[i])); resend(resendingIds[i], MTPCheckResendWaiting); } @@ -291,7 +291,7 @@ void Session::checkRequestsByTimer() { { QWriteLocker locker(data.haveSentMutex()); mtpRequestMap &haveSent(data.haveSentMap()); - for (uint32 i = 0, l = removingIds.size(); i < l; ++i) { + for (uint32_t i = 0, l = removingIds.size(); i < l; ++i) { mtpRequestMap::iterator j = haveSent.find(removingIds[i]); if (j != haveSent.cend()) { if (j.value()->requestId) { @@ -305,7 +305,7 @@ void Session::checkRequestsByTimer() { } } -void Session::onConnectionStateChange(qint32 newState) { +void Session::onConnectionStateChange(int32_t newState) { _instance->onStateChange(dcWithShift, newState); } @@ -329,12 +329,12 @@ void Session::ping() { sendAnything(0); } -int32 Session::requestState(mtpRequestId requestId) const { - int32 result = MTP::RequestSent; +int32_t Session::requestState(mtpRequestId requestId) const { + int32_t result = MTP::RequestSent; bool connected = false; if (_connection) { - int32 s = _connection->state(); + int32_t s = _connection->state(); if (s == ConnectedState) { connected = true; } else if (s == ConnectingState || s == DisconnectedState) { @@ -362,11 +362,11 @@ int32 Session::requestState(mtpRequestId requestId) const { } } -int32 Session::getState() const { - int32 result = -86400000; +int32_t Session::getState() const { + int32_t result = -86400000; if (_connection) { - int32 s = _connection->state(); + int32_t s = _connection->state(); if (s == ConnectedState) { return s; } else if (s == ConnectingState || s == DisconnectedState) { @@ -389,7 +389,7 @@ QString Session::transport() const { return _connection ? _connection->transport() : QString(); } -mtpRequestId Session::resend(quint64 msgId, qint64 msCanWait, bool forceContainer, bool sendMsgStateInfo) { +mtpRequestId Session::resend(uint64_t msgId, int64_t msCanWait, bool forceContainer, bool sendMsgStateInfo) { mtpRequest request; { QWriteLocker locker(data.haveSentMutex()); @@ -412,7 +412,7 @@ mtpRequestId Session::resend(quint64 msgId, qint64 msCanWait, bool forceContaine if (mtpRequestData::isSentContainer(request)) { // for container just resend all messages we can DEBUG_LOG(("Message Info: resending container from haveSent, msgId %1").arg(msgId)); const mtpMsgId *ids = (const mtpMsgId *)(request->constData() + 8); - for (uint32 i = 0, l = (request->size() - 8) >> 1; i < l; ++i) { + for (uint32_t i = 0, l = (request->size() - 8) >> 1; i < l; ++i) { resend(ids[i], 10, true); } return 0xFFFFFFFF; @@ -429,8 +429,8 @@ mtpRequestId Session::resend(quint64 msgId, qint64 msCanWait, bool forceContaine } } -void Session::resendMany(QVector msgIds, qint64 msCanWait, bool forceContainer, bool sendMsgStateInfo) { - for (int32 i = 0, l = msgIds.size(); i < l; ++i) { +void Session::resendMany(QVector msgIds, int64_t msCanWait, bool forceContainer, bool sendMsgStateInfo) { + for (int32_t i = 0, l = msgIds.size(); i < l; ++i) { resend(msgIds.at(i), msCanWait, forceContainer, sendMsgStateInfo); } } @@ -445,7 +445,7 @@ void Session::resendAll() { if (i.value()->requestId) toResend.push_back(i.key()); } } - for (uint32 i = 0, l = toResend.size(); i < l; ++i) { + for (uint32_t i = 0, l = toResend.size(); i < l; ++i) { resend(toResend[i], 10, true); } } @@ -504,7 +504,7 @@ void Session::destroyKey() { } } -int32 Session::getDcWithShift() const { +int32_t Session::getDcWithShift() const { return dcWithShift; } diff --git a/Telegram/SourceFiles/mtproto/session.h b/Telegram/SourceFiles/mtproto/session.h index 54559d0e5..acf724604 100644 --- a/Telegram/SourceFiles/mtproto/session.h +++ b/Telegram/SourceFiles/mtproto/session.h @@ -94,7 +94,7 @@ inline bool ResponseNeedsAck(const SerializedMessage &response) { if (response.size() < 8) { return false; } - auto seqNo = *(uint32*)(response.constData() + 6); + auto seqNo = *(uint32_t*)(response.constData() + 6); return (seqNo & 0x01) ? true : false; } @@ -104,7 +104,7 @@ public: SessionData(not_null creator) : _owner(creator) { } - void setSession(uint64 session) { + void setSession(uint64_t session) { DEBUG_LOG(("MTP Info: setting server_session: %1").arg(session)); QWriteLocker locker(&_lock); @@ -113,7 +113,7 @@ public: _messagesSent = 0; } } - uint64 getSession() const { + uint64_t getSession() const { QReadLocker locker(&_lock); return _session; } @@ -143,11 +143,11 @@ public: _cloudLangCode = code; } - void setSalt(uint64 salt) { + void setSalt(uint64_t salt) { QWriteLocker locker(&_lock); _salt = salt; } - uint64 getSalt() const { + uint64_t getSalt() const { QReadLocker locker(&_lock); return _salt; } @@ -246,7 +246,7 @@ public: return _owner; } - uint32 nextRequestSeqNumber(bool needAck = true) { + uint32_t nextRequestSeqNumber(bool needAck = true) { QWriteLocker locker(&_lock); auto result = _messagesSent; _messagesSent += (needAck ? 1 : 0); @@ -256,10 +256,10 @@ public: void clear(Instance *instance); private: - uint64 _session = 0; - uint64 _salt = 0; + uint64_t _session = 0; + uint64_t _salt = 0; - uint32 _messagesSent = 0; + uint32_t _messagesSent = 0; not_null _owner; @@ -316,8 +316,8 @@ public: void ping(); void cancel(mtpRequestId requestId, mtpMsgId msgId); - int32 requestState(mtpRequestId requestId) const; - int32 getState() const; + int32_t requestState(mtpRequestId requestId) const; + int32_t getState() const; QString transport() const; void sendPrepared(const mtpRequest &request, TimeMs msCanWait = 0, bool newRequest = true); // nulls msgId and seqNo in request, if newRequest = true @@ -333,8 +333,8 @@ signals: public slots: void needToResumeAndSend(); - mtpRequestId resend(quint64 msgId, qint64 msCanWait = 0, bool forceContainer = false, bool sendMsgStateInfo = false); - void resendMany(QVector msgIds, qint64 msCanWait, bool forceContainer, bool sendMsgStateInfo); + mtpRequestId resend(uint64_t msgId, int64_t msCanWait = 0, bool forceContainer = false, bool sendMsgStateInfo = false); + void resendMany(QVector msgIds, int64_t msCanWait, bool forceContainer, bool sendMsgStateInfo); void resendAll(); // after connection restart void authKeyCreatedForDC(); @@ -342,12 +342,12 @@ public slots: void tryToReceive(); void checkRequestsByTimer(); - void onConnectionStateChange(qint32 newState); + void onConnectionStateChange(int32_t newState); void onResetDone(); - void sendAnything(qint64 msCanWait = 0); - void sendPong(quint64 msgId, quint64 pingId); - void sendMsgsStateInfo(quint64 msgId, QByteArray data); + void sendAnything(int64_t msCanWait = 0); + void sendPong(uint64_t msgId, uint64_t pingId); + void sendMsgsStateInfo(uint64_t msgId, QByteArray data); private: void createDcData(); diff --git a/Telegram/SourceFiles/mtproto/special_config_request.cpp b/Telegram/SourceFiles/mtproto/special_config_request.cpp index f0d3295a7..d15fcb1a9 100644 --- a/Telegram/SourceFiles/mtproto/special_config_request.cpp +++ b/Telegram/SourceFiles/mtproto/special_config_request.cpp @@ -218,7 +218,7 @@ void SpecialConfigRequest::handleResponse(const QByteArray &bytes) { for (auto &entry : config.vip_port_list.v) { Assert(entry.type() == mtpc_ipPort); auto &ipPort = entry.c_ipPort(); - auto ip = *reinterpret_cast(&ipPort.vipv4.v); + auto ip = *reinterpret_cast(&ipPort.vipv4.v); auto ipString = qsl("%1.%2.%3.%4").arg((ip >> 24) & 0xFF).arg((ip >> 16) & 0xFF).arg((ip >> 8) & 0xFF).arg(ip & 0xFF); _callback(config.vdc_id.v, ipString.toStdString(), ipPort.vport.v); } diff --git a/Telegram/SourceFiles/mtproto/type_utils.h b/Telegram/SourceFiles/mtproto/type_utils.h index b843ba618..79edbd5df 100644 --- a/Telegram/SourceFiles/mtproto/type_utils.h +++ b/Telegram/SourceFiles/mtproto/type_utils.h @@ -47,7 +47,7 @@ namespace base {\ } // we use the same flags field for some additional client side flags -enum class MTPDmessage_ClientFlag : int32 { +enum class MTPDmessage_ClientFlag : int32_t { // message has links for "shared links" indexing f_has_text_links = (1 << 30), @@ -83,7 +83,7 @@ enum class MTPDmessage_ClientFlag : int32 { }; DEFINE_MTP_CLIENT_FLAGS(MTPDmessage) -enum class MTPDreplyKeyboardMarkup_ClientFlag : int32 { +enum class MTPDreplyKeyboardMarkup_ClientFlag : int32_t { // none (zero) markup f_zero = (1 << 30), @@ -101,7 +101,7 @@ enum class MTPDreplyKeyboardMarkup_ClientFlag : int32 { }; DEFINE_MTP_CLIENT_FLAGS(MTPDreplyKeyboardMarkup) -enum class MTPDstickerSet_ClientFlag : int32 { +enum class MTPDstickerSet_ClientFlag : int32_t { // old value for sticker set is not yet loaded flag f_not_loaded__old = (1 << 31), diff --git a/Telegram/SourceFiles/observer_peer.h b/Telegram/SourceFiles/observer_peer.h index ec3f1cc46..f181a3ef1 100644 --- a/Telegram/SourceFiles/observer_peer.h +++ b/Telegram/SourceFiles/observer_peer.h @@ -34,7 +34,7 @@ struct PeerUpdate { } PeerData *peer; - enum class Flag : uint32 { + enum class Flag : uint32_t { None = 0, // Common flags @@ -85,7 +85,7 @@ struct PeerUpdate { PeerData::NameFirstChars oldNameFirstChars; // SharedMediaChanged data - int32 mediaTypesMask = 0; + int32_t mediaTypesMask = 0; }; diff --git a/Telegram/SourceFiles/overview/overview_layout.cpp b/Telegram/SourceFiles/overview/overview_layout.cpp index 9dbd9de6a..616458a23 100644 --- a/Telegram/SourceFiles/overview/overview_layout.cpp +++ b/Telegram/SourceFiles/overview/overview_layout.cpp @@ -220,7 +220,7 @@ void Photo::initDimensions() { _minh = _maxw; } -int32 Photo::resizeGetHeight(int32 width) { +int32_t Photo::resizeGetHeight(int32_t width) { width = qMin(width, _maxw); if (width != _width || width != _height) { _width = qMin(width, _maxw); @@ -238,7 +238,7 @@ void Photo::paint(Painter &p, const QRect &clip, TextSelection selection, const if ((good && !_goodLoaded) || _pix.width() != _width * cIntRetinaFactor()) { _goodLoaded = good; - int32 size = _width * cIntRetinaFactor(); + int32_t size = _width * cIntRetinaFactor(); if (_goodLoaded || _data->thumb->loaded()) { auto img = (_data->loaded() ? _data->full : (_data->medium->loaded() ? _data->medium : _data->thumb))->pix().toImage(); if (!_goodLoaded) { @@ -320,7 +320,7 @@ void Video::initDimensions() { _minh = _maxw; } -int32 Video::resizeGetHeight(int32 width) { +int32_t Video::resizeGetHeight(int32_t width) { _width = qMin(width, _maxw); _height = _width; return _height; @@ -376,9 +376,9 @@ void Video::paint(Painter &p, const QRect &clip, TextSelection selection, const if (!selected && !context->selecting && !loaded) { if (clip.intersects(QRect(0, _height - st::normalFont->height, _width, st::normalFont->height))) { - int32 statusX = st::msgDateImgPadding.x(), statusY = _height - st::normalFont->height - st::msgDateImgPadding.y(); - int32 statusW = st::normalFont->width(_status.text()) + 2 * st::msgDateImgPadding.x(); - int32 statusH = st::normalFont->height + 2 * st::msgDateImgPadding.y(); + int32_t statusX = st::msgDateImgPadding.x(), statusY = _height - st::normalFont->height - st::msgDateImgPadding.y(); + int32_t statusW = st::normalFont->width(_status.text()) + 2 * st::msgDateImgPadding.x(); + int32_t statusH = st::normalFont->height + 2 * st::msgDateImgPadding.y(); statusX = _width - statusW + statusX; p.fillRect(rtlrect(statusX - st::msgDateImgPadding.x(), statusY - st::msgDateImgPadding.y(), statusW, statusH, _width), selected ? st::msgDateImgBgSelected : st::msgDateImgBg); p.setFont(st::normalFont); @@ -387,9 +387,9 @@ void Video::paint(Painter &p, const QRect &clip, TextSelection selection, const } } if (clip.intersects(QRect(0, 0, _width, st::normalFont->height))) { - int32 statusX = st::msgDateImgPadding.x(), statusY = st::msgDateImgPadding.y(); - int32 statusW = st::normalFont->width(_duration) + 2 * st::msgDateImgPadding.x(); - int32 statusH = st::normalFont->height + 2 * st::msgDateImgPadding.y(); + int32_t statusX = st::msgDateImgPadding.x(), statusY = st::msgDateImgPadding.y(); + int32_t statusW = st::normalFont->width(_duration) + 2 * st::msgDateImgPadding.x(); + int32_t statusH = st::normalFont->height + 2 * st::msgDateImgPadding.y(); p.fillRect(rtlrect(statusX - st::msgDateImgPadding.x(), statusY - st::msgDateImgPadding.y(), statusW, statusH, _width), selected ? st::msgDateImgBgSelected : st::msgDateImgBg); p.setFont(st::normalFont); p.setPen(st::msgDateImgFg); @@ -530,13 +530,13 @@ void Voice::paint(Painter &p, const QRect &clip, TextSelection selection, const } } bool showPause = updateStatusText(); - int32 nameVersion = _parent->fromOriginal()->nameVersion; + int32_t nameVersion = _parent->fromOriginal()->nameVersion; if (nameVersion > _nameVersion) { updateName(); } bool radial = isRadialAnimation(context->ms); - int32 nameleft = 0, nametop = 0, nameright = 0, statustop = 0, datetop = -1; + int32_t nameleft = 0, nametop = 0, nameright = 0, statustop = 0, datetop = -1; nameleft = _st.songPadding.left() + _st.songThumbSize + _st.songPadding.right(); nameright = _st.songPadding.left(); @@ -581,7 +581,7 @@ void Voice::paint(Painter &p, const QRect &clip, TextSelection selection, const icon->paintInCenter(p, inner); } - int32 namewidth = _width - nameleft - nameright; + int32_t namewidth = _width - nameleft - nameright; if (clip.intersects(rtlrect(nameleft, nametop, namewidth, st::semiboldFont->height, _width))) { p.setPen(st::historyFileNameInFg); @@ -591,14 +591,14 @@ void Voice::paint(Painter &p, const QRect &clip, TextSelection selection, const if (clip.intersects(rtlrect(nameleft, statustop, namewidth, st::normalFont->height, _width))) { p.setFont(st::normalFont); p.setPen(selected ? st::mediaInFgSelected : st::mediaInFg); - int32 unreadx = nameleft; + int32_t unreadx = nameleft; if (_status.size() == FileStatusSizeLoaded || _status.size() == FileStatusSizeReady) { p.setTextPalette(selected ? st::mediaInPaletteSelected : st::mediaInPalette); _details.drawLeftElided(p, nameleft, statustop, namewidth, _width); p.restoreTextPalette(); unreadx += _details.maxWidth(); } else { - int32 statusw = st::normalFont->width(_status.text()); + int32_t statusw = st::normalFont->width(_status.text()); p.drawTextLeft(nameleft, statustop, _width, _status.text(), statusw); unreadx += statusw; } @@ -617,7 +617,7 @@ void Voice::paint(Painter &p, const QRect &clip, TextSelection selection, const void Voice::getState(ClickHandlerPtr &link, HistoryCursorState &cursor, QPoint point) const { bool loaded = _data->loaded(); - int32 nameleft = 0, nametop = 0, nameright = 0, statustop = 0, datetop = 0; + int32_t nameleft = 0, nametop = 0, nameright = 0, statustop = 0, datetop = 0; nameleft = _st.songPadding.left() + _st.songThumbSize + _st.songPadding.right(); nameright = _st.songPadding.left(); @@ -659,7 +659,7 @@ void Voice::updateName() { bool Voice::updateStatusText() { bool showPause = false; - int32 statusSize = 0, realDuration = 0; + int32_t statusSize = 0, realDuration = 0; if (_data->status == FileDownloadFailed || _data->status == FileUploadFailed) { statusSize = FileStatusSizeFailed; } else if (_data->loaded()) { @@ -698,7 +698,7 @@ Document::Document(DocumentData *document, HistoryItem *parent, const style::Ove if (withThumb()) { _data->thumb->load(); - int32 tw = convertScale(_data->thumb->width()), th = convertScale(_data->thumb->height()); + int32_t tw = convertScale(_data->thumb->width()), th = convertScale(_data->thumb->height()); if (tw > th) { _thumbw = (tw * _st.fileThumbSize) / th; } else { @@ -739,7 +739,7 @@ void Document::paint(Painter &p, const QRect &clip, TextSelection selection, con bool showPause = updateStatusText(); bool radial = isRadialAnimation(context->ms); - int32 nameleft = 0, nametop = 0, nameright = 0, statustop = 0, datetop = -1; + int32_t nameleft = 0, nametop = 0, nameright = 0, statustop = 0, datetop = -1; bool wthumb = withThumb(); auto isSong = (_data->song() != nullptr); @@ -887,7 +887,7 @@ void Document::paint(Painter &p, const QRect &clip, TextSelection selection, con void Document::getState(ClickHandlerPtr &link, HistoryCursorState &cursor, QPoint point) const { bool loaded = _data->loaded() || Local::willStickerImageLoad(_data->mediaKey()); - int32 nameleft = 0, nametop = 0, nameright = 0, statustop = 0, datetop = 0; + int32_t nameleft = 0, nametop = 0, nameright = 0, statustop = 0, datetop = 0; bool wthumb = withThumb(); if (_data->song()) { @@ -939,7 +939,7 @@ void Document::getState(ClickHandlerPtr &link, HistoryCursorState &cursor, QPoin bool Document::updateStatusText() { bool showPause = false; - int32 statusSize = 0, realDuration = 0; + int32_t statusSize = 0, realDuration = 0; if (_data->status == FileDownloadFailed || _data->status == FileUploadFailed) { statusSize = FileStatusSizeFailed; } else if (_data->status == FileUploading) { @@ -979,7 +979,7 @@ Link::Link(HistoryMedia *media, HistoryItem *parent) : ItemBase(parent) { auto text = textWithEntities.text; auto &entities = textWithEntities.entities; - int32 from = 0, till = text.size(), lnk = entities.size(); + int32_t from = 0, till = text.size(), lnk = entities.size(); for_const (auto &entity, entities) { auto type = entity.type(); if (type != EntityInTextUrl && type != EntityInTextCustomUrl && type != EntityInTextEmail) { @@ -1000,7 +1000,7 @@ Link::Link(HistoryMedia *media, HistoryItem *parent) : ItemBase(parent) { ++lnk; break; } - int32 afterLinkStart = entity.offset() + entity.length(); + int32_t afterLinkStart = entity.offset() + entity.length(); if (till > afterLinkStart) { if (!QRegularExpression(qsl("^[,.\\s_=+\\-;:`'\"\\(\\)\\[\\]\\{\\}<>*&^%\\$#@!\\\\/]+$")).match(text.mid(afterLinkStart, till - afterLinkStart)).hasMatch()) { ++lnk; @@ -1040,10 +1040,10 @@ Link::Link(HistoryMedia *media, HistoryItem *parent) : ItemBase(parent) { till = text.size(); } if (till > from) { - TextParseOptions opts = { TextParseMultiline, int32(st::linksMaxWidth), 3 * st::normalFont->height, Qt::LayoutDirectionAuto }; + TextParseOptions opts = { TextParseMultiline, int32_t(st::linksMaxWidth), 3 * st::normalFont->height, Qt::LayoutDirectionAuto }; _text.setText(st::defaultTextStyle, text.mid(from, till - from), opts); } - int32 tw = 0, th = 0; + int32_t tw = 0, th = 0; if (_page && _page->photo) { if (!_page->photo->loaded()) _page->photo->thumb->load(false, false); @@ -1104,13 +1104,13 @@ void Link::initDimensions() { _minh += qMin(3 * st::normalFont->height, _text.countHeight(_maxw - st::linksPhotoSize - st::linksPhotoPadding)); } _minh += _links.size() * st::normalFont->height; - _minh = qMax(_minh, int32(st::linksPhotoSize)) + st::linksMargin.top() + st::linksMargin.bottom() + st::linksBorder; + _minh = qMax(_minh, int32_t(st::linksPhotoSize)) + st::linksMargin.top() + st::linksMargin.bottom() + st::linksBorder; } -int32 Link::resizeGetHeight(int32 width) { +int32_t Link::resizeGetHeight(int32_t width) { _width = qMin(width, _maxw); - int32 w = _width - st::linksPhotoSize - st::linksPhotoPadding; - for (int32 i = 0, l = _links.size(); i < l; ++i) { + int32_t w = _width - st::linksPhotoSize - st::linksPhotoPadding; + for (int32_t i = 0, l = _links.size(); i < l; ++i) { _links.at(i).lnk->setFullDisplayed(w >= _links.at(i).width); } @@ -1122,12 +1122,12 @@ int32 Link::resizeGetHeight(int32 width) { _height += qMin(3 * st::normalFont->height, _text.countHeight(_width - st::linksPhotoSize - st::linksPhotoPadding)); } _height += _links.size() * st::normalFont->height; - _height = qMax(_height, int32(st::linksPhotoSize)) + st::linksMargin.top() + st::linksMargin.bottom() + st::linksBorder; + _height = qMax(_height, int32_t(st::linksPhotoSize)) + st::linksMargin.top() + st::linksMargin.bottom() + st::linksBorder; return _height; } void Link::paint(Painter &p, const QRect &clip, TextSelection selection, const PaintContext *context) { - int32 left = st::linksPhotoSize + st::linksPhotoPadding, top = st::linksMargin.top() + st::linksBorder, w = _width - left; + int32_t left = st::linksPhotoSize + st::linksPhotoPadding, top = st::linksMargin.top() + st::linksBorder, w = _width - left; if (clip.intersects(rtlrect(0, top, st::linksPhotoSize, st::linksPhotoSize, _width))) { if (_page && _page->photo) { QPixmap pix; @@ -1143,7 +1143,7 @@ void Link::paint(Painter &p, const QRect &clip, TextSelection selection, const P auto roundRadius = _page->document->isRoundVideo() ? ImageRoundRadius::Ellipse : ImageRoundRadius::Small; p.drawPixmapLeft(0, top, _width, _page->document->thumb->pixSingle(_pixw, _pixh, st::linksPhotoSize, st::linksPhotoSize, roundRadius)); } else { - int32 index = _letter.isEmpty() ? 0 : (_letter.at(0).unicode() % 4); + int32_t index = _letter.isEmpty() ? 0 : (_letter.at(0).unicode() % 4); switch (index) { case 0: App::roundRect(p, rtlrect(0, top, st::linksPhotoSize, st::linksPhotoSize, _width), st::msgFile1Bg, Doc1Corners); break; case 1: App::roundRect(p, rtlrect(0, top, st::linksPhotoSize, st::linksPhotoSize, _width), st::msgFile2Bg, Doc2Corners); break; @@ -1182,7 +1182,7 @@ void Link::paint(Painter &p, const QRect &clip, TextSelection selection, const P } p.setFont(st::msgFont); if (!_text.isEmpty()) { - int32 h = qMin(st::normalFont->height * 3, _text.countHeight(w)); + int32_t h = qMin(st::normalFont->height * 3, _text.countHeight(w)); if (clip.intersects(rtlrect(left, top, w, h, _width))) { _text.drawLeftElided(p, left, top, w, _width, 3); } @@ -1190,7 +1190,7 @@ void Link::paint(Painter &p, const QRect &clip, TextSelection selection, const P } p.setPen(st::windowActiveTextFg); - for (int32 i = 0, l = _links.size(); i < l; ++i) { + for (int32_t i = 0, l = _links.size(); i < l; ++i) { if (clip.intersects(rtlrect(left, top, qMin(w, _links.at(i).width), st::normalFont->height, _width))) { p.setFont(ClickHandler::showAsActive(_links.at(i).lnk) ? st::normalFont->underline() : st::normalFont); p.drawTextLeft(left, top, _width, (w < _links.at(i).width) ? st::normalFont->elided(_links.at(i).text, w) : _links.at(i).text); @@ -1205,7 +1205,7 @@ void Link::paint(Painter &p, const QRect &clip, TextSelection selection, const P } void Link::getState(ClickHandlerPtr &link, HistoryCursorState &cursor, QPoint point) const { - int32 left = st::linksPhotoSize + st::linksPhotoPadding, top = st::linksMargin.top() + st::linksBorder, w = _width - left; + int32_t left = st::linksPhotoSize + st::linksPhotoPadding, top = st::linksMargin.top() + st::linksBorder, w = _width - left; if (rtlrect(0, top, st::linksPhotoSize, st::linksPhotoSize, _width).contains(point)) { link = _photol; return; @@ -1224,7 +1224,7 @@ void Link::getState(ClickHandlerPtr &link, HistoryCursorState &cursor, QPoint po if (!_text.isEmpty()) { top += qMin(st::normalFont->height * 3, _text.countHeight(w)); } - for (int32 i = 0, l = _links.size(); i < l; ++i) { + for (int32_t i = 0, l = _links.size(); i < l; ++i) { if (rtlrect(left, top, qMin(w, _links.at(i).width), st::normalFont->height, _width).contains(point)) { link = _links.at(i).lnk; return; diff --git a/Telegram/SourceFiles/overview/overview_layout.h b/Telegram/SourceFiles/overview/overview_layout.h index c3b28f4ad..a0eb5f9c3 100644 --- a/Telegram/SourceFiles/overview/overview_layout.h +++ b/Telegram/SourceFiles/overview/overview_layout.h @@ -122,7 +122,7 @@ protected: return _radial && _radial->animating(); } - virtual float64 dataProgress() const = 0; + virtual double dataProgress() const = 0; virtual bool dataFinished() const = 0; virtual bool dataLoaded() const = 0; virtual bool iconAnimated() const { @@ -182,7 +182,7 @@ public: Photo(PhotoData *photo, HistoryItem *parent); void initDimensions() override; - int32 resizeGetHeight(int32 width) override; + int32_t resizeGetHeight(int32_t width) override; void paint(Painter &p, const QRect &clip, TextSelection selection, const PaintContext *context) override; void getState(ClickHandlerPtr &link, HistoryCursorState &cursor, QPoint point) const override; @@ -209,7 +209,7 @@ public: Video(DocumentData *video, HistoryItem *parent); void initDimensions() override; - int32 resizeGetHeight(int32 width) override; + int32_t resizeGetHeight(int32_t width) override; void paint(Painter &p, const QRect &clip, TextSelection selection, const PaintContext *context) override; void getState(ClickHandlerPtr &link, HistoryCursorState &cursor, QPoint point) const override; @@ -219,7 +219,7 @@ public: void invalidateCache() override; protected: - float64 dataProgress() const override { + double dataProgress() const override { return _data->progress(); } bool dataFinished() const override { @@ -257,7 +257,7 @@ public: void getState(ClickHandlerPtr &link, HistoryCursorState &cursor, QPoint point) const override; protected: - float64 dataProgress() const override { + double dataProgress() const override { return _data->progress(); } bool dataFinished() const override { @@ -298,7 +298,7 @@ public: } protected: - float64 dataProgress() const override { + double dataProgress() const override { return _data->progress(); } bool dataFinished() const override { @@ -323,8 +323,8 @@ private: Text _name; QString _date, _ext; - int32 _datew, _extw; - int32 _thumbw, _colorIndex; + int32_t _datew, _extw; + int32_t _thumbw, _colorIndex; bool withThumb() const { return !_data->song() && !_data->thumb->isNull() && _data->thumb->width() && _data->thumb->height() && !documentIsExecutableName(_data->name); @@ -338,7 +338,7 @@ public: Link(HistoryMedia *media, HistoryItem *parent); void initDimensions() override; - int32 resizeGetHeight(int32 width) override; + int32_t resizeGetHeight(int32_t width) override; void paint(Painter &p, const QRect &clip, TextSelection selection, const PaintContext *context) override; void getState(ClickHandlerPtr &link, HistoryCursorState &cursor, QPoint point) const override; @@ -357,7 +357,7 @@ private: } LinkEntry(const QString &url, const QString &text); QString text; - int32 width; + int32_t width; TextClickHandlerPtr lnk; }; QVector _links; diff --git a/Telegram/SourceFiles/overviewwidget.cpp b/Telegram/SourceFiles/overviewwidget.cpp index 71f994483..4e2aadfd0 100644 --- a/Telegram/SourceFiles/overviewwidget.cpp +++ b/Telegram/SourceFiles/overviewwidget.cpp @@ -179,18 +179,18 @@ MsgId OverviewInner::itemMsgId(MsgId msgId) const { return itemMigrated(msgId) ? -msgId : msgId; } -int32 OverviewInner::migratedIndexSkip() const { +int32_t OverviewInner::migratedIndexSkip() const { return (_migrated && _history->overviewLoaded(_type)) ? _migrated->overview(_type).size() : 0; } -void OverviewInner::fixItemIndex(int32 ¤t, MsgId msgId) const { +void OverviewInner::fixItemIndex(int32_t ¤t, MsgId msgId) const { if (!msgId) { current = -1; } else { - int32 l = _items.size(); + int32_t l = _items.size(); if (current < 0 || current >= l || complexMsgId(_items.at(current)->getItem()) != msgId) { current = -1; - for (int32 i = 0; i < l; ++i) { + for (int32_t i = 0; i < l; ++i) { if (complexMsgId(_items.at(i)->getItem()) == msgId) { current = i; break; @@ -296,7 +296,7 @@ bool OverviewInner::searchFailed(SearchRequestType type, const RPCError &error, return true; } -bool OverviewInner::itemHasPoint(MsgId msgId, int32 index, int32 x, int32 y) const { +bool OverviewInner::itemHasPoint(MsgId msgId, int32_t index, int32_t x, int32_t y) const { fixItemIndex(index, msgId); if (index < 0) return false; @@ -312,7 +312,7 @@ bool OverviewInner::itemHasPoint(MsgId msgId, int32 index, int32 x, int32 y) con return false; } -int32 OverviewInner::itemHeight(MsgId msgId, int32 index) const { +int32_t OverviewInner::itemHeight(MsgId msgId, int32_t index) const { if (_type == OverviewPhotos || _type == OverviewVideos) { return _rowWidth; } @@ -321,7 +321,7 @@ int32 OverviewInner::itemHeight(MsgId msgId, int32 index) const { return (index < 0) ? 0 : _items.at(index)->height(); } -void OverviewInner::moveToNextItem(MsgId &msgId, int32 &index, MsgId upTo, int32 delta) const { +void OverviewInner::moveToNextItem(MsgId &msgId, int32_t &index, MsgId upTo, int32_t delta) const { fixItemIndex(index, msgId); if (msgId == upTo || index < 0) { msgId = 0; @@ -341,16 +341,16 @@ void OverviewInner::moveToNextItem(MsgId &msgId, int32 &index, MsgId upTo, int32 } } -void OverviewInner::repaintItem(MsgId itemId, int32 itemIndex) { +void OverviewInner::repaintItem(MsgId itemId, int32_t itemIndex) { fixItemIndex(itemIndex, itemId); if (itemIndex >= 0) { if (_type == OverviewPhotos || _type == OverviewVideos) { - float64 w = (float64(_width - st::overviewPhotoSkip) / _photosInRow); - int32 vsize = (_rowWidth + st::overviewPhotoSkip); - int32 row = itemIndex / _photosInRow, col = itemIndex % _photosInRow; - update(int32(col * w), _marginTop + int32(row * vsize), qCeil(w), vsize); + double w = (double(_width - st::overviewPhotoSkip) / _photosInRow); + int32_t vsize = (_rowWidth + st::overviewPhotoSkip); + int32_t row = itemIndex / _photosInRow, col = itemIndex % _photosInRow; + update(int32_t(col * w), _marginTop + int32_t(row * vsize), qCeil(w), vsize); } else { - int32 top = _items.at(itemIndex)->Get()->top; + int32_t top = _items.at(itemIndex)->Get()->top; if (_reversed) top = _height - top; update(_rowsLeft, _marginTop + top, _rowWidth, _items.at(itemIndex)->height()); } @@ -362,9 +362,9 @@ void OverviewInner::touchResetSpeed() { _touchPrevPosValid = false; } -void OverviewInner::touchDeaccelerate(int32 elapsed) { - int32 x = _touchSpeed.x(); - int32 y = _touchSpeed.y(); +void OverviewInner::touchDeaccelerate(int32_t elapsed) { + int32_t x = _touchSpeed.x(); + int32_t y = _touchSpeed.y(); _touchSpeed.setX((x == 0) ? x : (x > 0) ? qMax(0, x - elapsed) : qMin(0, x + elapsed)); _touchSpeed.setY((y == 0) ? y : (y > 0) ? qMax(0, y - elapsed) : qMin(0, y + elapsed)); } @@ -648,9 +648,9 @@ void OverviewInner::touchScrollUpdated(const QPoint &screenPos) { touchUpdateSpeed(); } -void OverviewInner::addSelectionRange(int32 selFrom, int32 selTo, History *history) { +void OverviewInner::addSelectionRange(int32_t selFrom, int32_t selTo, History *history) { if (selFrom < 0 || selTo < 0) return; - for (int32 i = selFrom; i <= selTo; ++i) { + for (int32_t i = selFrom; i <= selTo; ++i) { MsgId msgid = complexMsgId(_items.at(i)->getItem()); if (!msgid) continue; @@ -683,17 +683,17 @@ void OverviewInner::applyDragSelection() { _overview->updateTopBarSelection(); } -QPoint OverviewInner::mapMouseToItem(QPoint p, MsgId itemId, int32 itemIndex) { +QPoint OverviewInner::mapMouseToItem(QPoint p, MsgId itemId, int32_t itemIndex) { fixItemIndex(itemIndex, itemId); if (itemIndex < 0) return QPoint(0, 0); if (_type == OverviewPhotos || _type == OverviewVideos) { - int32 row = itemIndex / _photosInRow, col = itemIndex % _photosInRow; - float64 w = (_width - st::overviewPhotoSkip) / float64(_photosInRow); - p.setX(p.x() - int32(col * w) - st::overviewPhotoSkip); + int32_t row = itemIndex / _photosInRow, col = itemIndex % _photosInRow; + double w = (_width - st::overviewPhotoSkip) / double(_photosInRow); + p.setX(p.x() - int32_t(col * w) - st::overviewPhotoSkip); p.setY(p.y() - _marginTop - row * (_rowWidth + st::overviewPhotoSkip) - st::overviewPhotoSkip); } else { - int32 top = _items.at(itemIndex)->Get()->top; + int32_t top = _items.at(itemIndex)->Get()->top; if (_reversed) top = _height - top; p.setY(p.y() - _marginTop - top); } @@ -726,12 +726,12 @@ void OverviewInner::clear() { App::clearMousedItems(); } -int32 OverviewInner::itemTop(const FullMsgId &msgId) const { +int32_t OverviewInner::itemTop(const FullMsgId &msgId) const { if (_type == OverviewMusicFiles) { - int32 itemIndex = -1; + int32_t itemIndex = -1; fixItemIndex(itemIndex, (msgId.channel == _channel) ? msgId.msg : ((_migrated && msgId.channel == _migrated->channelId()) ? -msgId.msg : 0)); if (itemIndex >= 0) { - int32 top = _items.at(itemIndex)->Get()->top; + int32_t top = _items.at(itemIndex)->Get()->top; if (_reversed) top = _height - top; return _marginTop + top; } @@ -768,8 +768,8 @@ bool OverviewInner::preloadLocal() { return true; } -TextSelection OverviewInner::itemSelectedValue(int32 index) const { - int32 selfrom = -1, selto = -1; +TextSelection OverviewInner::itemSelectedValue(int32_t index) const { + int32_t selfrom = -1, selto = -1; if (_dragSelFromIndex >= 0 && _dragSelToIndex >= 0) { selfrom = _dragSelToIndex; selto = _dragSelFromIndex; @@ -810,7 +810,7 @@ void OverviewInner::paintEvent(QPaintEvent *e) { return; } - int32 selfrom = -1, selto = -1; + int32_t selfrom = -1, selto = -1; if (_dragSelFromIndex >= 0 && _dragSelToIndex >= 0) { selfrom = _dragSelToIndex; selto = _dragSelFromIndex; @@ -820,18 +820,18 @@ void OverviewInner::paintEvent(QPaintEvent *e) { bool hasSel = !_selected.isEmpty(); if (_type == OverviewPhotos || _type == OverviewVideos) { - int32 count = _items.size(), rowsCount = count / _photosInRow + ((count % _photosInRow) ? 1 : 0); - int32 rowFrom = floorclamp(r.y() - _marginTop - st::overviewPhotoSkip, _rowWidth + st::overviewPhotoSkip, 0, rowsCount); - int32 rowTo = ceilclamp(r.y() + r.height() - _marginTop - st::overviewPhotoSkip, _rowWidth + st::overviewPhotoSkip, 0, rowsCount); - float64 w = float64(_width - st::overviewPhotoSkip) / _photosInRow; - for (int32 row = rowFrom; row < rowTo; ++row) { + int32_t count = _items.size(), rowsCount = count / _photosInRow + ((count % _photosInRow) ? 1 : 0); + int32_t rowFrom = floorclamp(r.y() - _marginTop - st::overviewPhotoSkip, _rowWidth + st::overviewPhotoSkip, 0, rowsCount); + int32_t rowTo = ceilclamp(r.y() + r.height() - _marginTop - st::overviewPhotoSkip, _rowWidth + st::overviewPhotoSkip, 0, rowsCount); + double w = double(_width - st::overviewPhotoSkip) / _photosInRow; + for (int32_t row = rowFrom; row < rowTo; ++row) { if (row * _photosInRow >= count) break; - for (int32 col = 0; col < _photosInRow; ++col) { - int32 i = row * _photosInRow + col; + for (int32_t col = 0; col < _photosInRow; ++col) { + int32_t i = row * _photosInRow + col; if (i < 0) continue; if (i >= count) break; - QPoint pos(int32(col * w + st::overviewPhotoSkip), _marginTop + row * (_rowWidth + st::overviewPhotoSkip) + st::overviewPhotoSkip); + QPoint pos(int32_t(col * w + st::overviewPhotoSkip), _marginTop + row * (_rowWidth + st::overviewPhotoSkip) + st::overviewPhotoSkip); p.translate(pos.x(), pos.y()); _items.at(i)->paint(p, r.translated(-pos.x(), -pos.y()), itemSelectedValue(i), &context); p.translate(-pos.x(), -pos.y()); @@ -839,14 +839,14 @@ void OverviewInner::paintEvent(QPaintEvent *e) { } } else { p.translate(_rowsLeft, _marginTop); - int32 y = 0, w = _rowWidth; - for (int32 j = 0, l = _items.size(); j < l; ++j) { - int32 i = _reversed ? (l - j - 1) : j, nexti = _reversed ? (i - 1) : (i + 1); - int32 nextItemTop = (j + 1 == l) ? (_reversed ? 0 : _height) : _items.at(nexti)->Get()->top; + int32_t y = 0, w = _rowWidth; + for (int32_t j = 0, l = _items.size(); j < l; ++j) { + int32_t i = _reversed ? (l - j - 1) : j, nexti = _reversed ? (i - 1) : (i + 1); + int32_t nextItemTop = (j + 1 == l) ? (_reversed ? 0 : _height) : _items.at(nexti)->Get()->top; if (_reversed) nextItemTop = _height - nextItemTop; if (_marginTop + nextItemTop > r.top()) { auto info = _items.at(i)->Get(); - int32 curY = info->top; + int32_t curY = info->top; if (_reversed) curY = _height - curY; if (_marginTop + curY >= r.y() + r.height()) break; @@ -875,18 +875,18 @@ void OverviewInner::onUpdateSelected() { ClickHandlerPtr lnk; ClickHandlerHost *lnkhost = nullptr; HistoryItem *item = 0; - int32 index = -1; - int32 newsel = 0; + int32_t index = -1; + int32_t newsel = 0; HistoryCursorState cursorState = HistoryDefaultCursorState; if (_type == OverviewPhotos || _type == OverviewVideos) { - float64 w = (float64(_width - st::overviewPhotoSkip) / _photosInRow); - int32 col = int32((m.x() - (st::overviewPhotoSkip / 2)) / w), vsize = (_rowWidth + st::overviewPhotoSkip); - int32 row = int32((m.y() - _marginTop - (st::overviewPhotoSkip / 2)) / vsize); + double w = (double(_width - st::overviewPhotoSkip) / _photosInRow); + int32_t col = int32_t((m.x() - (st::overviewPhotoSkip / 2)) / w), vsize = (_rowWidth + st::overviewPhotoSkip); + int32_t row = int32_t((m.y() - _marginTop - (st::overviewPhotoSkip / 2)) / vsize); if (col < 0) col = 0; if (row < 0) row = 0; bool upon = true; - int32 count = _items.size(), i = row * _photosInRow + col; + int32_t count = _items.size(), i = row * _photosInRow + col; if (i < 0) { i = 0; upon = false; @@ -906,16 +906,16 @@ void OverviewInner::onUpdateSelected() { } } } else { - for (int32 j = 0, l = _items.size(); j < l; ++j) { + for (int32_t j = 0, l = _items.size(); j < l; ++j) { bool lastItem = (j + 1 == l); - int32 i = _reversed ? (l - j - 1) : j, nexti = _reversed ? (i - 1) : (i + 1); - int32 nextItemTop = lastItem ? (_reversed ? 0 : _height) : _items.at(nexti)->Get()->top; + int32_t i = _reversed ? (l - j - 1) : j, nexti = _reversed ? (i - 1) : (i + 1); + int32_t nextItemTop = lastItem ? (_reversed ? 0 : _height) : _items.at(nexti)->Get()->top; if (_reversed) nextItemTop = _height - nextItemTop; if (_marginTop + nextItemTop > m.y() || lastItem) { - int32 top = _items.at(i)->Get()->top; + int32_t top = _items.at(i)->Get()->top; if (_reversed) top = _height - top; if (!_items.at(i)->toMediaItem()) { // day item - int32 h = _items.at(i)->height(); + int32_t h = _items.at(i)->height(); bool beforeItem = (_marginTop + top + h / 2) >= m.y(); if (_reversed) beforeItem = !beforeItem; if (i > 0 && (beforeItem || i == _items.size() - 1)) { @@ -945,7 +945,7 @@ void OverviewInner::onUpdateSelected() { } MsgId oldMousedItem = _mousedItem; - int32 oldMousedItemIndex = _mousedItemIndex; + int32_t oldMousedItemIndex = _mousedItemIndex; _mousedItem = item ? ((item->history() == _migrated) ? -item->id : item->id) : 0; _mousedItemIndex = index; m = mapMouseToItem(m, _mousedItem, _mousedItemIndex); @@ -994,13 +994,13 @@ void OverviewInner::onUpdateSelected() { bool canSelectMany = (_peer != 0); if (_mousedItem == _dragItem && lnk && !_selected.isEmpty() && _selected.cbegin().value() != FullSelection) { bool afterSymbol = false, uponSymbol = false; - uint16 second = 0; + uint16_t second = 0; _selected[_dragItem] = { 0, 0 }; updateDragSelection(0, -1, 0, -1, false); } else if (canSelectMany) { bool selectingDown = (_reversed ? (_mousedItemIndex < _dragItemIndex) : (_mousedItemIndex > _dragItemIndex)) || (_mousedItemIndex == _dragItemIndex && ((_type == OverviewPhotos || _type == OverviewVideos) ? (_dragStartPos.x() < m.x()) : (_dragStartPos.y() < m.y()))); MsgId dragSelFrom = _dragItem, dragSelTo = _mousedItem; - int32 dragSelFromIndex = _dragItemIndex, dragSelToIndex = _mousedItemIndex; + int32_t dragSelFromIndex = _dragItemIndex, dragSelToIndex = _mousedItemIndex; if (!itemHasPoint(dragSelFrom, dragSelFromIndex, _dragStartPos.x(), _dragStartPos.y())) { // maybe exclude dragSelFrom if (selectingDown) { if (_type == OverviewPhotos || _type == OverviewVideos) { @@ -1049,7 +1049,7 @@ void OverviewInner::onUpdateSelected() { } bool dragSelecting = false; MsgId dragFirstAffected = dragSelFrom; - int32 dragFirstAffectedIndex = dragSelFromIndex; + int32_t dragFirstAffectedIndex = dragSelFromIndex; while (dragFirstAffectedIndex >= 0 && itemMsgId(dragFirstAffected) <= 0) { moveToNextItem(dragFirstAffected, dragFirstAffectedIndex, dragSelTo, selectingDown ? (_reversed ? -1 : 1) : (_reversed ? 1 : -1)); } @@ -1097,7 +1097,7 @@ QString OverviewInner::tooltipText() const { return QString(); } -void OverviewInner::updateDragSelection(MsgId dragSelFrom, int32 dragSelFromIndex, MsgId dragSelTo, int32 dragSelToIndex, bool dragSelecting) { +void OverviewInner::updateDragSelection(MsgId dragSelFrom, int32_t dragSelFromIndex, MsgId dragSelTo, int32_t dragSelToIndex, bool dragSelecting) { if (_dragSelFrom != dragSelFrom || _dragSelFromIndex != dragSelFromIndex || _dragSelTo != dragSelTo || _dragSelToIndex != dragSelToIndex || _dragSelecting != dragSelecting) { _dragSelFrom = dragSelFrom; _dragSelFromIndex = dragSelFromIndex; @@ -1180,7 +1180,7 @@ void OverviewInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) { auto selectedState = getSelectionState(); // -2 - has full selected items, but not over, 0 - no selection, 2 - over full selected items - int32 isUponSelected = 0, hasSelected = 0; + int32_t isUponSelected = 0, hasSelected = 0; if (!_selected.isEmpty()) { isUponSelected = -1; if (_selected.cbegin().value() == FullSelection) { @@ -1293,19 +1293,19 @@ void OverviewInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) { } } -int32 OverviewInner::resizeToWidth(int32 nwidth, int32 scrollTop, int32 minHeight, bool force) { +int32_t OverviewInner::resizeToWidth(int32_t nwidth, int32_t scrollTop, int32_t minHeight, bool force) { if (!force && _width == nwidth && minHeight == _minHeight) return scrollTop; if ((_type == OverviewPhotos || _type == OverviewVideos) && _resizeIndex < 0) { - _resizeIndex = _photosInRow * ((scrollTop + minHeight) / int32(_rowWidth + st::overviewPhotoSkip)) + _photosInRow - 1; - _resizeSkip = (scrollTop + minHeight) - ((scrollTop + minHeight) / int32(_rowWidth + st::overviewPhotoSkip)) * int32(_rowWidth + st::overviewPhotoSkip); + _resizeIndex = _photosInRow * ((scrollTop + minHeight) / int32_t(_rowWidth + st::overviewPhotoSkip)) + _photosInRow - 1; + _resizeSkip = (scrollTop + minHeight) - ((scrollTop + minHeight) / int32_t(_rowWidth + st::overviewPhotoSkip)) * int32_t(_rowWidth + st::overviewPhotoSkip); } _width = nwidth; _minHeight = minHeight; if (_type == OverviewPhotos || _type == OverviewVideos) { - _photosInRow = int32(_width - st::overviewPhotoSkip) / int32(st::overviewPhotoMinSize + st::overviewPhotoSkip); - _rowWidth = (int32(_width - st::overviewPhotoSkip) / _photosInRow) - st::overviewPhotoSkip; + _photosInRow = int32_t(_width - st::overviewPhotoSkip) / int32_t(st::overviewPhotoMinSize + st::overviewPhotoSkip); + _rowWidth = (int32_t(_width - st::overviewPhotoSkip) / _photosInRow) - st::overviewPhotoSkip; _rowsLeft = st::overviewPhotoSkip; } else { auto contentLeftMin = st::overviewLeftMin; @@ -1316,7 +1316,7 @@ int32 OverviewInner::resizeToWidth(int32 nwidth, int32 scrollTop, int32 minHeigh } auto widthWithMin = st::windowMinWidth; auto widthWithMax = st::overviewFileLayout.maxWidth + 2 * contentLeftMax; - _rowsLeft = anim::interpolate(contentLeftMax, contentLeftMin, qMax(widthWithMax - _width, 0) / float64(widthWithMax - widthWithMin)); + _rowsLeft = anim::interpolate(contentLeftMax, contentLeftMin, qMax(widthWithMax - _width, 0) / double(widthWithMax - widthWithMin)); _rowWidth = qMin(_width - 2 * _rowsLeft, st::overviewFileLayout.maxWidth); } @@ -1329,8 +1329,8 @@ int32 OverviewInner::resizeToWidth(int32 nwidth, int32 scrollTop, int32 minHeigh resize(_width, _marginTop + _height + _marginBottom); if (_type == OverviewPhotos || _type == OverviewVideos) { - int32 newRow = _resizeIndex / _photosInRow; - return newRow * int32(_rowWidth + st::overviewPhotoSkip) + _resizeSkip - minHeight; + int32_t newRow = _resizeIndex / _photosInRow; + return newRow * int32_t(_rowWidth + st::overviewPhotoSkip) + _resizeSkip - minHeight; } return scrollTop; } @@ -1608,7 +1608,7 @@ void OverviewInner::onTouchScrollTimer() { _touchScrollState = Ui::TouchScrollState::Manual; touchResetSpeed(); } else if (_touchScrollState == Ui::TouchScrollState::Auto || _touchScrollState == Ui::TouchScrollState::Acceleration) { - int32 elapsed = int32(nowTime - _touchTime); + int32_t elapsed = int32_t(nowTime - _touchTime); QPoint delta = _touchSpeed * elapsed / 1000; bool hasScrolled = _overview->touchScroll(delta); @@ -1742,7 +1742,7 @@ void OverviewInner::mediaOverviewUpdated() { fixItemIndex(_dragItemIndex, _dragItem); recountMargins(); - int32 newHeight = _marginTop + _height + _marginBottom, deltaHeight = newHeight - height(); + int32_t newHeight = _marginTop + _height + _marginBottom, deltaHeight = newHeight - height(); if (deltaHeight) { resize(_width, newHeight); if (_type == OverviewMusicFiles || _type == OverviewVoiceFiles) { @@ -1798,7 +1798,7 @@ void OverviewInner::itemRemoved(HistoryItem *item) { auto j = _layoutItems.find(item); if (j != _layoutItems.cend()) { - int32 index = _items.indexOf(j.value()); + int32_t index = _items.indexOf(j.value()); if (index >= 0) { _items.remove(index); } @@ -1825,25 +1825,25 @@ void OverviewInner::repaintItem(const HistoryItem *msg) { History *history = (msg->history() == _history) ? _history : (msg->history() == _migrated ? _migrated : 0); if (!history) return; - int32 migrateindex = migratedIndexSkip(); + int32_t migrateindex = migratedIndexSkip(); MsgId msgid = msg->id; if ((history == _history || migrateindex > 0) && (_inSearch || history->overviewHasMsgId(_type, msgid))) { if (_type == OverviewPhotos || _type == OverviewVideos) { if (history == _migrated) msgid = -msgid; - for (int32 i = 0, l = _items.size(); i != l; ++i) { + for (int32_t i = 0, l = _items.size(); i != l; ++i) { if (complexMsgId(_items.at(i)->getItem()) == msgid) { - float64 w = (float64(width() - st::overviewPhotoSkip) / _photosInRow); - int32 vsize = (_rowWidth + st::overviewPhotoSkip); - int32 row = i / _photosInRow, col = i % _photosInRow; - update(int32(col * w), _marginTop + int32(row * vsize), qCeil(w), vsize); + double w = (double(width() - st::overviewPhotoSkip) / _photosInRow); + int32_t vsize = (_rowWidth + st::overviewPhotoSkip); + int32_t row = i / _photosInRow, col = i % _photosInRow; + update(int32_t(col * w), _marginTop + int32_t(row * vsize), qCeil(w), vsize); break; } } } else { if (history == _migrated) msgid = -msgid; - for (int32 i = 0, l = _items.size(); i != l; ++i) { + for (int32_t i = 0, l = _items.size(); i != l; ++i) { if (complexMsgId(_items.at(i)->getItem()) == msgid) { - int32 top = _items.at(i)->Get()->top; + int32_t top = _items.at(i)->Get()->top; if (_reversed) top = _height - top; update(_rowsLeft, _marginTop + top, _rowWidth, _items.at(i)->height()); break; @@ -1870,13 +1870,13 @@ void OverviewInner::recountMargins() { _marginTop = 0; } else if (_type == OverviewMusicFiles) { _marginTop = st::playlistPadding; - _marginBottom = qMax(_minHeight - _height - _marginTop, int32(st::playlistPadding)); + _marginBottom = qMax(_minHeight - _height - _marginTop, int32_t(st::playlistPadding)); } else if (_type == OverviewLinks || _type == OverviewFiles) { _marginTop = st::linksSearchTop + _search->height(); - _marginBottom = qMax(_minHeight - _height - _marginTop, int32(st::playlistPadding)); + _marginBottom = qMax(_minHeight - _height - _marginTop, int32_t(st::playlistPadding)); } else { _marginBottom = st::playlistPadding; - _marginTop = qMax(_minHeight - _height - _marginBottom, int32(st::playlistPadding)); + _marginTop = qMax(_minHeight - _height - _marginBottom, int32_t(st::playlistPadding)); } } @@ -1923,7 +1923,7 @@ Overview::Layout::ItemBase *OverviewInner::layoutPrepare(HistoryItem *item) { } Overview::Layout::AbstractItem *OverviewInner::layoutPrepare(const QDate &date, bool month) { - int32 key = date.year() * 100 + date.month(); + int32_t key = date.year() * 100 + date.month(); if (!month) key = key * 100 + date.day(); LayoutDates::const_iterator i = _layoutDates.constFind(key); if (i == _layoutDates.cend()) { @@ -1933,13 +1933,13 @@ Overview::Layout::AbstractItem *OverviewInner::layoutPrepare(const QDate &date, return i.value(); } -int32 OverviewInner::setLayoutItem(int32 index, Overview::Layout::AbstractItem *item, int32 top) { +int32_t OverviewInner::setLayoutItem(int32_t index, Overview::Layout::AbstractItem *item, int32_t top) { if (_items.size() > index) { _items[index] = item; } else { _items.push_back(item); } - int32 h = item->resizeGetHeight(_rowWidth); + int32_t h = item->resizeGetHeight(_rowWidth); if (auto info = item->Get()) { info->top = top + (_reversed ? h : 0); } @@ -1981,7 +1981,7 @@ void OverviewWidget::clear() { void OverviewWidget::onScroll() { Auth().downloader().clearPriorities(); - int32 preloadThreshold = _scroll->height() * 5; + int32_t preloadThreshold = _scroll->height() * 5; bool needToPreload = false; do { needToPreload = (type() == OverviewMusicFiles || type() == OverviewVoiceFiles) ? (_scroll->scrollTop() < preloadThreshold) : (_scroll->scrollTop() + preloadThreshold > _scroll->scrollTopMax()); @@ -2049,7 +2049,7 @@ void OverviewWidget::contextMenuEvent(QContextMenuEvent *e) { return _inner->showContextMenu(e); } -void OverviewWidget::scrollBy(int32 add) { +void OverviewWidget::scrollBy(int32_t add) { if (_scroll->isHidden()) { _scrollSetAfterShow += add; } else { @@ -2112,7 +2112,7 @@ void OverviewWidget::switchType(MediaOverviewType type) { } bool OverviewWidget::showMediaTypeSwitch() const { - for (int32 i = 0; i < OverviewCount; ++i) { + for (int32_t i = 0; i < OverviewCount; ++i) { if (!(_mediaTypeMask & ~(1 << i))) { return false; } @@ -2137,11 +2137,11 @@ void OverviewWidget::updateTopBarSelection() { update(); } -int32 OverviewWidget::lastWidth() const { +int32_t OverviewWidget::lastWidth() const { return width(); } -int32 OverviewWidget::lastScrollTop() const { +int32_t OverviewWidget::lastScrollTop() const { return _scroll->scrollTop(); } @@ -2153,11 +2153,11 @@ QRect OverviewWidget::rectForFloatPlayer(Window::Column myColumn, Window::Column return mapToGlobal(_scroll->geometry()); } -int32 OverviewWidget::countBestScroll() const { +int32_t OverviewWidget::countBestScroll() const { if (type() == OverviewMusicFiles) { auto state = Media::Player::mixer()->currentState(AudioMsgId::Type::Song); if (state.id) { - int32 top = _inner->itemTop(state.id.contextId()); + int32_t top = _inner->itemTop(state.id.contextId()); if (top >= 0) { return snap(top - int(_scroll->height() - (st::msgPadding.top() + st::mediaThumbSize + st::msgPadding.bottom())) / 2, 0, _scroll->scrollTopMax()); } @@ -2168,7 +2168,7 @@ int32 OverviewWidget::countBestScroll() const { return _scroll->scrollTopMax(); } -void OverviewWidget::fastShow(bool back, int32 lastScrollTop) { +void OverviewWidget::fastShow(bool back, int32_t lastScrollTop) { resizeEvent(0); _scrollSetAfterShow = (lastScrollTop < 0 ? countBestScroll() : lastScrollTop); show(); @@ -2236,11 +2236,11 @@ void OverviewWidget::mediaOverviewUpdated(const Notify::PeerUpdate &update) { onScroll(); updateTopBarSelection(); } - int32 mask = 0; + int32_t mask = 0; History *h = update.peer ? App::historyLoaded(update.peer->migrateTo() ? update.peer->migrateTo() : update.peer) : nullptr; History *m = (update.peer && update.peer->migrateFrom()) ? App::historyLoaded(update.peer->migrateFrom()->id) : 0; if (h) { - for (int32 i = 0; i < OverviewCount; ++i) { + for (int32_t i = 0; i < OverviewCount; ++i) { if (!h->overview(i).isEmpty() || h->overviewCount(i) > 0 || i == type()) { mask |= (1 << i); } else if (m && (!m->overview(i).isEmpty() || m->overviewCount(i) > 0)) { @@ -2334,7 +2334,7 @@ QPoint OverviewWidget::clampMousePosition(QPoint point) { } void OverviewWidget::onScrollTimer() { - int32 d = (_scrollDelta > 0) ? qMin(_scrollDelta * 3 / 20 + 1, int32(MaxScrollSpeed)) : qMax(_scrollDelta * 3 / 20 - 1, -int32(MaxScrollSpeed)); + int32_t d = (_scrollDelta > 0) ? qMin(_scrollDelta * 3 / 20 + 1, int32_t(MaxScrollSpeed)) : qMax(_scrollDelta * 3 / 20 - 1, -int32_t(MaxScrollSpeed)); _scroll->scrollToY(_scroll->scrollTop() + d); } @@ -2358,7 +2358,7 @@ void OverviewWidget::noSelectingScroll() { } bool OverviewWidget::touchScroll(const QPoint &delta) { - int32 scTop = _scroll->scrollTop(), scMax = _scroll->scrollTopMax(), scNew = snap(scTop - delta.y(), 0, scMax); + int32_t scTop = _scroll->scrollTop(), scMax = _scroll->scrollTopMax(), scNew = snap(scTop - delta.y(), 0, scMax); if (scNew == scTop) return false; _scroll->scrollToY(scNew); diff --git a/Telegram/SourceFiles/overviewwidget.h b/Telegram/SourceFiles/overviewwidget.h index adde68249..e78c961e0 100644 --- a/Telegram/SourceFiles/overviewwidget.h +++ b/Telegram/SourceFiles/overviewwidget.h @@ -62,7 +62,7 @@ public: void activate(); void clear(); - int32 itemTop(const FullMsgId &msgId) const; + int32_t itemTop(const FullMsgId &msgId) const; bool preloadLocal(); void preloadMore(); @@ -75,9 +75,9 @@ public: void dragActionCancel(); void touchScrollUpdated(const QPoint &screenPos); - QPoint mapMouseToItem(QPoint p, MsgId itemId, int32 itemIndex); + QPoint mapMouseToItem(QPoint p, MsgId itemId, int32_t itemIndex); - int32 resizeToWidth(int32 nwidth, int32 scrollTop, int32 minHeight, bool force = false); // returns new scroll top + int32_t resizeToWidth(int32_t nwidth, int32_t scrollTop, int32_t minHeight, bool force = false); // returns new scroll top void dropResizeIndex(); PeerData *peer() const; @@ -148,23 +148,23 @@ private: bool itemMigrated(MsgId msgId) const; ChannelId itemChannel(MsgId msgId) const; MsgId itemMsgId(MsgId msgId) const; - int32 migratedIndexSkip() const; + int32_t migratedIndexSkip() const; - void fixItemIndex(int32 ¤t, MsgId msgId) const; - bool itemHasPoint(MsgId msgId, int32 index, int32 x, int32 y) const; - int32 itemHeight(MsgId msgId, int32 index) const; - void moveToNextItem(MsgId &msgId, int32 &index, MsgId upTo, int32 delta) const; + void fixItemIndex(int32_t ¤t, MsgId msgId) const; + bool itemHasPoint(MsgId msgId, int32_t index, int32_t x, int32_t y) const; + int32_t itemHeight(MsgId msgId, int32_t index) const; + void moveToNextItem(MsgId &msgId, int32_t &index, MsgId upTo, int32_t delta) const; - void updateDragSelection(MsgId dragSelFrom, int32 dragSelFromIndex, MsgId dragSelTo, int32 dragSelToIndex, bool dragSelecting); + void updateDragSelection(MsgId dragSelFrom, int32_t dragSelFromIndex, MsgId dragSelTo, int32_t dragSelToIndex, bool dragSelecting); - void repaintItem(MsgId itemId, int32 itemIndex); + void repaintItem(MsgId itemId, int32_t itemIndex); void touchResetSpeed(); void touchUpdateSpeed(); - void touchDeaccelerate(int32 elapsed); + void touchDeaccelerate(int32_t elapsed); void applyDragSelection(); - void addSelectionRange(int32 selFrom, int32 selTo, History *history); + void addSelectionRange(int32_t selFrom, int32_t selTo, History *history); void recountMargins(); int countHeight(); @@ -182,7 +182,7 @@ private: ChannelId _channel; bool _selMode = false; - TextSelection itemSelectedValue(int32 index) const; + TextSelection itemSelectedValue(int32_t index) const; int _rowsLeft = 0; int _rowWidth = 0; @@ -191,19 +191,19 @@ private: Items _items; typedef QMap LayoutItems; LayoutItems _layoutItems; - typedef QMap LayoutDates; + typedef QMap LayoutDates; LayoutDates _layoutDates; Overview::Layout::ItemBase *layoutPrepare(HistoryItem *item); Overview::Layout::AbstractItem *layoutPrepare(const QDate &date, bool month); - int32 setLayoutItem(int32 index, Overview::Layout::AbstractItem *item, int32 top); + int32_t setLayoutItem(int32_t index, Overview::Layout::AbstractItem *item, int32_t top); object_ptr _search; object_ptr _cancelSearch; QVector _results; - int32 _itemsToBeLoaded; + int32_t _itemsToBeLoaded; // photos - int32 _photosInRow = 1; + int32_t _photosInRow = 1; QTimer _searchTimer; QString _searchQuery; @@ -257,7 +257,7 @@ private: int _dragItemIndex = -1; MsgId _mousedItem = 0; int _mousedItemIndex = -1; - uint16 _dragSymbol; + uint16_t _dragSymbol; bool _dragWasInactive = false; ClickHandlerPtr _contextMenuLnk; @@ -294,7 +294,7 @@ public: void clear(); - void scrollBy(int32 add); + void scrollBy(int32_t add); void scrollReset(); bool paintTopBar(Painter &p, int decreaseWidth); @@ -307,11 +307,11 @@ public: void updateTopBarSelection(); bool contentOverlapped(const QRect &globalRect); - int32 lastWidth() const; - int32 lastScrollTop() const; - int32 countBestScroll() const; + int32_t lastWidth() const; + int32_t lastScrollTop() const; + int32_t countBestScroll() const; - void fastShow(bool back = false, int32 lastScrollTop = -1); + void fastShow(bool back = false, int32_t lastScrollTop = -1); bool hasTopBarShadow() const { return true; } @@ -336,7 +336,7 @@ public: _inGrab = true; resizeEvent(0); } - void grapWithoutTopBarShadow(); + void grapWithoutTopBarShadow();//@fixme grab? void grabFinish() override; void rpcClear() override { _inner->rpcClear(); @@ -383,7 +383,7 @@ private: bool _noDropResizeIndex = false; object_ptr _mediaType; - int32 _mediaTypeMask = 0; + int32_t _mediaTypeMask = 0; QString _header; @@ -391,10 +391,10 @@ private: Window::SlideDirection _showDirection; QPixmap _cacheUnder, _cacheOver; - int32 _scrollSetAfterShow = 0; + int32_t _scrollSetAfterShow = 0; QTimer _scrollTimer; - int32 _scrollDelta = 0; + int32_t _scrollDelta = 0; object_ptr _topShadow; bool _inGrab = false; diff --git a/Telegram/SourceFiles/platform/linux/linux_libnotify.cpp b/Telegram/SourceFiles/platform/linux/linux_libnotify.cpp index 4f969d918..9ec06978b 100644 --- a/Telegram/SourceFiles/platform/linux/linux_libnotify.cpp +++ b/Telegram/SourceFiles/platform/linux/linux_libnotify.cpp @@ -63,8 +63,8 @@ f_notify_notification_set_timeout notify_notification_set_timeout = nullptr; //f_notify_notification_set_icon_from_pixbuf notify_notification_set_icon_from_pixbuf = nullptr; f_notify_notification_set_image_from_pixbuf notify_notification_set_image_from_pixbuf = nullptr; //f_notify_notification_set_hint notify_notification_set_hint = nullptr; -//f_notify_notification_set_hint_int32 notify_notification_set_hint_int32 = nullptr; -//f_notify_notification_set_hint_uint32 notify_notification_set_hint_uint32 = nullptr; +//f_notify_notification_set_hint_int32_t notify_notification_set_hint_int32_t = nullptr; +//f_notify_notification_set_hint_uint32_t notify_notification_set_hint_uint32_t = nullptr; //f_notify_notification_set_hint_double notify_notification_set_hint_double = nullptr; f_notify_notification_set_hint_string notify_notification_set_hint_string = nullptr; //f_notify_notification_set_hint_byte notify_notification_set_hint_byte = nullptr; @@ -105,8 +105,8 @@ void startLibNotify() { // load(lib_notify, "notify_notification_set_icon_from_pixbuf", notify_notification_set_icon_from_pixbuf); load(lib_notify, "notify_notification_set_image_from_pixbuf", notify_notification_set_image_from_pixbuf); // load(lib_notify, "notify_notification_set_hint", notify_notification_set_hint); -// load(lib_notify, "notify_notification_set_hint_int32", notify_notification_set_hint_int32); -// load(lib_notify, "notify_notification_set_hint_uint32", notify_notification_set_hint_uint32); +// load(lib_notify, "notify_notification_set_hint_int32_t", notify_notification_set_hint_int32_t); +// load(lib_notify, "notify_notification_set_hint_uint32_t", notify_notification_set_hint_uint32_t); // load(lib_notify, "notify_notification_set_hint_double", notify_notification_set_hint_double); load(lib_notify, "notify_notification_set_hint_string", notify_notification_set_hint_string); // load(lib_notify, "notify_notification_set_hint_byte", notify_notification_set_hint_byte); diff --git a/Telegram/SourceFiles/platform/linux/linux_libnotify.h b/Telegram/SourceFiles/platform/linux/linux_libnotify.h index c23f32432..a567dd406 100644 --- a/Telegram/SourceFiles/platform/linux/linux_libnotify.h +++ b/Telegram/SourceFiles/platform/linux/linux_libnotify.h @@ -95,11 +95,11 @@ extern f_notify_notification_set_image_from_pixbuf notify_notification_set_image //using f_notify_notification_set_hint = void (*)(NotifyNotification *notification, const char *key, GVariant *value); //extern f_notify_notification_set_hint notify_notification_set_hint; -//using f_notify_notification_set_hint_int32 = void (*)(NotifyNotification *notification, const char *key, gint value); -//extern f_notify_notification_set_hint_int32 notify_notification_set_hint_int32; +//using f_notify_notification_set_hint_int32_t = void (*)(NotifyNotification *notification, const char *key, gint value); +//extern f_notify_notification_set_hint_int32_t notify_notification_set_hint_int32_t; -//using f_notify_notification_set_hint_uint32 = void (*)(NotifyNotification *notification, const char *key, guint value); -//extern f_notify_notification_set_hint_uint32 notify_notification_set_hint_uint32; +//using f_notify_notification_set_hint_uint32_t = void (*)(NotifyNotification *notification, const char *key, guint value); +//extern f_notify_notification_set_hint_uint32_t notify_notification_set_hint_uint32_t; //using f_notify_notification_set_hint_double = void (*)(NotifyNotification *notification, const char *key, gdouble value); //extern f_notify_notification_set_hint_double notify_notification_set_hint_double; diff --git a/Telegram/SourceFiles/platform/linux/linux_libs.h b/Telegram/SourceFiles/platform/linux/linux_libs.h index e9e349be9..5e608c954 100644 --- a/Telegram/SourceFiles/platform/linux/linux_libs.h +++ b/Telegram/SourceFiles/platform/linux/linux_libs.h @@ -190,7 +190,7 @@ extern f_gdk_set_allowed_backends gdk_set_allowed_backends; typedef void (*f_gdk_window_set_modal_hint)(GdkWindow *window, gboolean modal); extern f_gdk_window_set_modal_hint gdk_window_set_modal_hint; -typedef void (*f_gdk_window_focus)(GdkWindow *window, guint32 timestamp); +typedef void (*f_gdk_window_focus)(GdkWindow *window, guint32_t timestamp); extern f_gdk_window_focus gdk_window_focus; typedef GTypeInstance* (*f_g_type_check_instance_cast)(GTypeInstance *instance, GType iface_type); @@ -341,10 +341,10 @@ extern f_gtk_status_icon_get_geometry gtk_status_icon_get_geometry; typedef void (*f_gtk_status_icon_position_menu)(GtkMenu *menu, gint *x, gint *y, gboolean *push_in, gpointer user_data); extern f_gtk_status_icon_position_menu gtk_status_icon_position_menu; -typedef void (*f_gtk_menu_popup)(GtkMenu *menu, GtkWidget *parent_menu_shell, GtkWidget *parent_menu_item, GtkMenuPositionFunc func, gpointer data, guint button, guint32 activate_time); +typedef void (*f_gtk_menu_popup)(GtkMenu *menu, GtkWidget *parent_menu_shell, GtkWidget *parent_menu_item, GtkMenuPositionFunc func, gpointer data, guint button, guint32_t activate_time); extern f_gtk_menu_popup gtk_menu_popup; -typedef guint32 (*f_gtk_get_current_event_time)(void); +typedef guint32_t (*f_gtk_get_current_event_time)(void); extern f_gtk_get_current_event_time gtk_get_current_event_time; typedef gpointer (*f_g_object_ref_sink)(gpointer object); @@ -375,7 +375,7 @@ typedef void (*f_g_slist_free)(GSList *list); extern f_g_slist_free g_slist_free; #ifndef TDESKTOP_DISABLE_UNITY_INTEGRATION -typedef void (*f_unity_launcher_entry_set_count)(UnityLauncherEntry* self, gint64 value); +typedef void (*f_unity_launcher_entry_set_count)(UnityLauncherEntry* self, gint64_t value); extern f_unity_launcher_entry_set_count unity_launcher_entry_set_count; typedef void (*f_unity_launcher_entry_set_count_visible)(UnityLauncherEntry* self, gboolean value); diff --git a/Telegram/SourceFiles/platform/linux/main_window_linux.cpp b/Telegram/SourceFiles/platform/linux/main_window_linux.cpp index e7c40a699..741a44bb9 100644 --- a/Telegram/SourceFiles/platform/linux/main_window_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/main_window_linux.cpp @@ -45,13 +45,13 @@ QByteArray _trayPixbufData; QList > _trayItems; #endif // !TDESKTOP_DISABLE_GTK_INTEGRATION -int32 _trayIconSize = 22; +int32_t _trayIconSize = 22; bool _trayIconMuted = true; -int32 _trayIconCount = 0; +int32_t _trayIconCount = 0; QImage _trayIconImageBack, _trayIconImage; #ifndef TDESKTOP_DISABLE_GTK_INTEGRATION -void _trayIconPopup(GtkStatusIcon *status_icon, guint button, guint32 activate_time, gpointer popup_menu) { +void _trayIconPopup(GtkStatusIcon *status_icon, guint button, guint32_t activate_time, gpointer popup_menu) { Libs::gtk_menu_popup(Libs::gtk_menu_cast(popup_menu), NULL, NULL, Libs::gtk_status_icon_position_menu, status_icon, button, activate_time); } @@ -83,7 +83,7 @@ gboolean _trayIconResized(GtkStatusIcon *status_icon, gint size, gpointer popup_ #endif // !TDESKTOP_DISABLE_GTK_INTEGRATION QImage _trayIconImageGen() { - int32 counter = App::histories().unreadBadge(), counterSlice = (counter >= 1000) ? (1000 + (counter % 100)) : counter; + int32_t counter = App::histories().unreadBadge(), counterSlice = (counter >= 1000) ? (1000 + (counter % 100)) : counter; bool muted = App::histories().unreadOnlyMuted(); if (_trayIconImage.isNull() || _trayIconImage.width() != _trayIconSize || muted != _trayIconMuted || counterSlice != _trayIconCount) { if (_trayIconImageBack.isNull() || _trayIconImageBack.width() != _trayIconSize) { @@ -91,9 +91,9 @@ QImage _trayIconImageGen() { _trayIconImageBack = _trayIconImageBack.convertToFormat(QImage::Format_ARGB32); int w = _trayIconImageBack.width(), h = _trayIconImageBack.height(), perline = _trayIconImageBack.bytesPerLine(); uchar *bytes = _trayIconImageBack.bits(); - for (int32 y = 0; y < h; ++y) { - for (int32 x = 0; x < w; ++x) { - int32 srcoff = y * perline + x * 4; + for (int32_t y = 0; y < h; ++y) { + for (int32_t x = 0; x < w; ++x) { + int32_t srcoff = y * perline + x * 4; bytes[srcoff + QT_RED ] = qMax(bytes[srcoff + QT_RED ], uchar(224)); bytes[srcoff + QT_GREEN] = qMax(bytes[srcoff + QT_GREEN], uchar(165)); bytes[srcoff + QT_BLUE ] = qMax(bytes[srcoff + QT_BLUE ], uchar(44)); @@ -103,7 +103,7 @@ QImage _trayIconImageGen() { _trayIconImage = _trayIconImageBack; if (counter > 0) { QPainter p(&_trayIconImage); - int32 layerSize = -16; + int32_t layerSize = -16; if (_trayIconSize >= 48) { layerSize = -32; } else if (_trayIconSize >= 36) { @@ -121,7 +121,7 @@ QImage _trayIconImageGen() { } QString _trayIconImageFile() { - int32 counter = App::histories().unreadBadge(), counterSlice = (counter >= 1000) ? (1000 + (counter % 100)) : counter; + int32_t counter = App::histories().unreadBadge(), counterSlice = (counter >= 1000) ? (1000 + (counter % 100)) : counter; bool muted = App::histories().unreadOnlyMuted(); QString name = cWorkingDir() + qsl("tdata/ticons/ico%1_%2_%3.png").arg(muted ? "mute" : "").arg(_trayIconSize).arg(counterSlice); @@ -145,9 +145,9 @@ void loadPixbuf(QImage image) { int w = image.width(), h = image.height(), perline = image.bytesPerLine(), s = image.byteCount(); _trayPixbufData.resize(w * h * 4); uchar *result = (uchar*)_trayPixbufData.data(), *bytes = image.bits(); - for (int32 y = 0; y < h; ++y) { - for (int32 x = 0; x < w; ++x) { - int32 offset = (y * w + x) * 4, srcoff = y * perline + x * 4; + for (int32_t y = 0; y < h; ++y) { + for (int32_t x = 0; x < w; ++x) { + int32_t offset = (y * w + x) * 4, srcoff = y * perline + x * 4; result[offset + GTK_RED ] = bytes[srcoff + QT_RED ]; result[offset + GTK_GREEN] = bytes[srcoff + QT_GREEN]; result[offset + GTK_BLUE ] = bytes[srcoff + QT_BLUE ]; @@ -160,7 +160,7 @@ void loadPixbuf(QImage image) { } void _trayMenuCallback(GtkMenu *menu, gpointer data) { - for (int32 i = 0, l = _trayItems.size(); i < l; ++i) { + for (int32_t i = 0, l = _trayItems.size(); i < l; ++i) { if ((void*)_trayItems.at(i).first == (void*)menu) { QMetaObject::invokeMethod(_trayItems.at(i).second, "triggered"); } @@ -226,7 +226,7 @@ void MainWindow::psTrayMenuUpdated() { const QList &actions = trayIconMenu->actions(); if (_trayItems.isEmpty()) { DEBUG_LOG(("Creating tray menu!")); - for (int32 i = 0, l = actions.size(); i != l; ++i) { + for (int32_t i = 0, l = actions.size(); i != l; ++i) { GtkWidget *item = Libs::gtk_menu_item_new_with_label(actions.at(i)->text().toUtf8()); Libs::gtk_menu_shell_append(Libs::gtk_menu_shell_cast(_trayMenu), item); Libs::g_signal_connect_helper(item, "activate", G_CALLBACK(_trayMenuCallback), this); @@ -237,7 +237,7 @@ void MainWindow::psTrayMenuUpdated() { } } else { DEBUG_LOG(("Updating tray menu!")); - for (int32 i = 0, l = actions.size(); i != l; ++i) { + for (int32_t i = 0, l = actions.size(); i != l; ++i) { if (i < _trayItems.size()) { Libs::gtk_menu_item_set_label(reinterpret_cast(_trayItems.at(i).first), actions.at(i)->text().toUtf8()); Libs::gtk_widget_set_sensitive(_trayItems.at(i).first, actions.at(i)->isEnabled()); @@ -380,7 +380,7 @@ void MainWindow::updateIconCounters() { QByteArray path = QFile::encodeName(iconFile.absoluteFilePath()); icon = QIcon(path.constData()); } else { - int32 counter = App::histories().unreadBadge(); + int32_t counter = App::histories().unreadBadge(); bool muted = App::histories().unreadOnlyMuted(); auto &bg = (muted ? st::trayCounterBgMute : st::trayCounterBg); diff --git a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp index 1bc0a146c..e56b9fe78 100644 --- a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp @@ -49,8 +49,8 @@ bool LibNotifyLoaded() { // && (Libs::notify_notification_set_icon_from_pixbuf != nullptr) && (Libs::notify_notification_set_image_from_pixbuf != nullptr) // && (Libs::notify_notification_set_hint != nullptr) -// && (Libs::notify_notification_set_hint_int32 != nullptr) -// && (Libs::notify_notification_set_hint_uint32 != nullptr) +// && (Libs::notify_notification_set_hint_int32_t != nullptr) +// && (Libs::notify_notification_set_hint_uint32_t != nullptr) // && (Libs::notify_notification_set_hint_double != nullptr) && (Libs::notify_notification_set_hint_string != nullptr) // && (Libs::notify_notification_set_hint_byte != nullptr) diff --git a/Telegram/SourceFiles/platform/linux/specific_linux.cpp b/Telegram/SourceFiles/platform/linux/specific_linux.cpp index fd478d86e..89d54cad9 100644 --- a/Telegram/SourceFiles/platform/linux/specific_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/specific_linux.cpp @@ -123,7 +123,7 @@ QString demanglestr(const QString &mangled) { return result.trimmed(); } -QStringList addr2linestr(uint64 *addresses, int count) { +QStringList addr2linestr(uint64_t *addresses, int count) { QStringList result; if (!count || cExeName().isEmpty()) return result; @@ -171,10 +171,10 @@ QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { QString initial = QString::fromUtf8(crashdump), result; QStringList lines = initial.split('\n'); result.reserve(initial.size()); - int32 i = 0, l = lines.size(); + int32_t i = 0, l = lines.size(); while (i < l) { - uint64 addresses[1024] = { 0 }; + uint64_t addresses[1024] = { 0 }; for (; i < l; ++i) { result.append(lines.at(i)).append('\n'); QString line = lines.at(i).trimmed(); @@ -184,7 +184,7 @@ QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { } } - int32 start = i; + int32_t start = i; for (; i < l; ++i) { QString line = lines.at(i).trimmed(); if (line.isEmpty()) break; @@ -193,7 +193,7 @@ QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { QRegularExpressionMatch m2 = QRegularExpression(qsl("^(.+)\\[(.+)\\]$")).match(line); QString addrstr = m1.hasMatch() ? m1.captured(4) : (m2.hasMatch() ? m2.captured(2) : QString()); if (!addrstr.isEmpty()) { - uint64 addr = addrstr.startsWith(qstr("0x")) ? addrstr.mid(2).toULongLong(0, 16) : addrstr.toULongLong(); + uint64_t addr = addrstr.startsWith(qstr("0x")) ? addrstr.mid(2).toULongLong(0, 16) : addrstr.toULongLong(); if (addr > 1) { addresses[i - start] = addr; } @@ -295,7 +295,7 @@ TimeMs psIdleTime() { return getms(true) - _lastUserAction; } -void psActivateProcess(uint64 pid) { +void psActivateProcess(uint64_t pid) { // objc_activateProgram(); } diff --git a/Telegram/SourceFiles/platform/linux/specific_linux.h b/Telegram/SourceFiles/platform/linux/specific_linux.h index f66519431..cea198a04 100644 --- a/Telegram/SourceFiles/platform/linux/specific_linux.h +++ b/Telegram/SourceFiles/platform/linux/specific_linux.h @@ -63,7 +63,7 @@ TimeMs psIdleTime(); QStringList psInitLogs(); void psClearInitLogs(); -void psActivateProcess(uint64 pid = 0); +void psActivateProcess(uint64_t pid = 0); QString psLocalServerPrefix(); QString psAppDataPath(); QString psDownloadPath(); diff --git a/Telegram/SourceFiles/platform/mac/file_utilities_mac.mm b/Telegram/SourceFiles/platform/mac/file_utilities_mac.mm index 5ec91732b..40c8bfe49 100644 --- a/Telegram/SourceFiles/platform/mac/file_utilities_mac.mm +++ b/Telegram/SourceFiles/platform/mac/file_utilities_mac.mm @@ -18,6 +18,7 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/mac/file_utilities_mac.h" #include "platform/mac/mac_utilities.h" @@ -31,17 +32,17 @@ namespace { using namespace Platform; QString strNeedToReload() { - const uint32 letters[] = { 0x82007746, 0xBB00C649, 0x7E00235F, 0x9A00FE54, 0x4C004542, 0x91001772, 0x8A00D76F, 0xC700B977, 0x7F005F73, 0x34003665, 0x2300D572, 0x72002E54, 0x18001461, 0x14004A62, 0x5100CC6C, 0x83002365, 0x5A002C56, 0xA5004369, 0x26004265, 0x0D006577 }; + const uint32_t letters[] = { 0x82007746, 0xBB00C649, 0x7E00235F, 0x9A00FE54, 0x4C004542, 0x91001772, 0x8A00D76F, 0xC700B977, 0x7F005F73, 0x34003665, 0x2300D572, 0x72002E54, 0x18001461, 0x14004A62, 0x5100CC6C, 0x83002365, 0x5A002C56, 0xA5004369, 0x26004265, 0x0D006577 }; return strMakeFromLetters(letters); } QString strNeedToRefresh1() { - const uint32 letters[] = { 0xEF006746, 0xF500CE49, 0x1500715F, 0x95001254, 0x3A00CB4C, 0x17009469, 0xB400DA73, 0xDE00C574, 0x9200EC56, 0x3C00A669, 0xFD00D865, 0x59000977 }; + const uint32_t letters[] = { 0xEF006746, 0xF500CE49, 0x1500715F, 0x95001254, 0x3A00CB4C, 0x17009469, 0xB400DA73, 0xDE00C574, 0x9200EC56, 0x3C00A669, 0xFD00D865, 0x59000977 }; return strMakeFromLetters(letters); } QString strNeedToRefresh2() { - const uint32 letters[] = { 0x8F001546, 0xAF007A49, 0xB8002B5F, 0x1A000B54, 0x0D003E49, 0xE0003663, 0x4900796F, 0x0500836E, 0x9A00D156, 0x5E00FF69, 0x5900C765, 0x3D00D177 }; + const uint32_t letters[] = { 0x8F001546, 0xAF007A49, 0xB8002B5F, 0x1A000B54, 0x0D003E49, 0xE0003663, 0x4900796F, 0x0500836E, 0x9A00D156, 0x5E00FF69, 0x5900C765, 0x3D00D177 }; return strMakeFromLetters(letters); } @@ -529,7 +530,7 @@ bool UnsafeShowOpenWith(const QString &filepath) { NSArray *appsPaths = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationDirectory inDomains:NSLocalDomainMask]; if ([appsPaths count]) [openPanel setDirectoryURL:[appsPaths firstObject]]; [openPanel beginWithCompletionHandler:^(NSInteger result){ - if (result == NSFileHandlingPanelOKButton) { + if (result == NSModalResponseOK) { if ([[openPanel URLs] count] > 0) { NSURL *app = [[openPanel URLs] objectAtIndex:0]; NSString *path = [app path]; diff --git a/Telegram/SourceFiles/platform/mac/mac_iconv_helper.c b/Telegram/SourceFiles/platform/mac/mac_iconv_helper.c deleted file mode 100644 index 82f72a5da..000000000 --- a/Telegram/SourceFiles/platform/mac/mac_iconv_helper.c +++ /dev/null @@ -1,45 +0,0 @@ -/* -This file is part of Telegram Desktop, -the official desktop version of Telegram messaging app, see https://telegram.org - -Telegram Desktop is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -It is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -In addition, as a special exception, the copyright holders give permission -to link the code of portions of this program with the OpenSSL library. - -Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE -Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org -*/ -#include - -#ifdef iconv_open -#undef iconv_open -#endif // iconv_open - -#ifdef iconv -#undef iconv -#endif // iconv - -#ifdef iconv_close -#undef iconv_close -#endif // iconv_close - -iconv_t iconv_open(const char* tocode, const char* fromcode) { - return libiconv_open(tocode, fromcode); -} - -size_t iconv(iconv_t cd, char** inbuf, size_t *inbytesleft, char** outbuf, size_t *outbytesleft) { - return libiconv(cd, inbuf, inbytesleft, outbuf, outbytesleft); -} - -int iconv_close(iconv_t cd) { - return libiconv_close(cd); -} diff --git a/Telegram/SourceFiles/platform/mac/mac_utilities.mm b/Telegram/SourceFiles/platform/mac/mac_utilities.mm index 020fed534..0106f3b97 100644 --- a/Telegram/SourceFiles/platform/mac/mac_utilities.mm +++ b/Telegram/SourceFiles/platform/mac/mac_utilities.mm @@ -15,4 +15,5 @@ GNU General Public License for more details. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/mac/mac_utilities.h" diff --git a/Telegram/SourceFiles/platform/mac/main_window_mac.mm b/Telegram/SourceFiles/platform/mac/main_window_mac.mm index b433bcb64..e6d70d10d 100644 --- a/Telegram/SourceFiles/platform/mac/main_window_mac.mm +++ b/Telegram/SourceFiles/platform/mac/main_window_mac.mm @@ -15,6 +15,7 @@ GNU General Public License for more details. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/mac/main_window_mac.h" #include "styles/style_window.h" @@ -161,7 +162,7 @@ void MainWindow::Private::setWindowBadge(const QString &str) { } void MainWindow::Private::initCustomTitle(NSWindow *window, NSView *view) { - [window setStyleMask:[window styleMask] | NSFullSizeContentViewWindowMask]; + [window setStyleMask:[window styleMask] | NSWindowStyleMaskFullSizeContentView]; [window setTitlebarAppearsTransparent:YES]; auto inner = [window contentLayoutRect]; auto full = [view frame]; @@ -197,7 +198,7 @@ void MainWindow::Private::enableShadow(WId winId) { bool MainWindow::Private::filterNativeEvent(void *event) { NSEvent *e = static_cast(event); - if (e && [e type] == NSSystemDefined && [e subtype] == SPSystemDefinedEventMediaKeys) { + if (e && [e type] == NSEventTypeSystemDefined && [e subtype] == SPSystemDefinedEventMediaKeys) { #ifndef OS_MAC_STORE // If event tap is not installed, handle events that reach the app instead if (![SPMediaKeyTap usesGlobalMediaKeyTap]) { @@ -225,7 +226,7 @@ MainWindow::MainWindow() void MainWindow::closeWithoutDestroy() { NSWindow *nsWindow = [reinterpret_cast(winId()) window]; - auto isFullScreen = (([nsWindow styleMask] & NSFullScreenWindowMask) == NSFullScreenWindowMask); + auto isFullScreen = (([nsWindow styleMask] & NSWindowStyleMaskFullScreen) == NSWindowStyleMaskFullScreen); if (isFullScreen) { _hideAfterFullScreenTimer.callOnce(kHideAfterFullscreenTimeoutMs); [nsWindow toggleFullScreen:nsWindow]; @@ -315,7 +316,7 @@ void _placeCounter(QImage &img, int size, int count, style::color bg, style::col p.setBrush(bg); p.setPen(Qt::NoPen); - int32 fontSize, skip; + int32_t fontSize, skip; if (size == 22) { skip = 1; fontSize = 8; @@ -324,7 +325,7 @@ void _placeCounter(QImage &img, int size, int count, style::color bg, style::col fontSize = 16; } style::font f(fontSize, 0, 0); - int32 w = f->width(cnt), d, r; + int32_t w = f->width(cnt), d, r; if (size == 22) { d = (cntSize < 2) ? 3 : 2; r = (cntSize < 2) ? 6 : 5; @@ -366,7 +367,7 @@ void MainWindow::updateIconCounters() { QImage img(psTrayIcon(dm)), imgsel(psTrayIcon(true)); img.detach(); imgsel.detach(); - int32 size = cRetina() ? 44 : 22; + int32_t size = cRetina() ? 44 : 22; _placeCounter(img, size, counter, bg, (dm && muted) ? st::trayCounterFgMacInvert : st::trayCounterFg); _placeCounter(imgsel, size, counter, st::trayCounterBgMacInvert, st::trayCounterFgMacInvert); icon.addPixmap(App::pixmapFromImageInPlace(std::move(img))); diff --git a/Telegram/SourceFiles/platform/mac/notifications_manager_mac.mm b/Telegram/SourceFiles/platform/mac/notifications_manager_mac.mm index d6e8e5d92..70bad8ce1 100644 --- a/Telegram/SourceFiles/platform/mac/notifications_manager_mac.mm +++ b/Telegram/SourceFiles/platform/mac/notifications_manager_mac.mm @@ -18,6 +18,7 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/mac/notifications_manager_mac.h" #include "platform/platform_specific.h" @@ -61,7 +62,7 @@ NSImage *qt_mac_create_nsimage(const QPixmap &pm); @interface NotificationDelegate : NSObject { } -- (id) initWithManager:(base::weak_unique_ptr)manager managerId:(uint64)managerId; +- (id) initWithManager:(base::weak_unique_ptr)manager managerId:(uint64_t)managerId; - (void) userNotificationCenter:(NSUserNotificationCenter*)center didActivateNotification:(NSUserNotification*)notification; - (BOOL) userNotificationCenter:(NSUserNotificationCenter*)center shouldPresentNotification:(NSUserNotification*)notification; @@ -69,11 +70,11 @@ NSImage *qt_mac_create_nsimage(const QPixmap &pm); @implementation NotificationDelegate { base::weak_unique_ptr _manager; - uint64 _managerId; + uint64_t _managerId; } -- (id) initWithManager:(base::weak_unique_ptr)manager managerId:(uint64)managerId { +- (id) initWithManager:(base::weak_unique_ptr)manager managerId:(uint64_t)managerId { if (self = [super init]) { _manager = manager; _managerId = managerId; @@ -185,7 +186,7 @@ private: void clearingThreadLoop(); - const uint64 _managerId = 0; + const uint64_t _managerId = 0; QString _managerIdString; NotificationDelegate *_delegate = nullptr; @@ -207,7 +208,7 @@ private: }; Manager::Private::Private(Manager *manager) -: _managerId(rand_value()) +: _managerId(rand_value()) , _managerIdString(QString::number(_managerId)) , _delegate([[NotificationDelegate alloc] initWithManager:manager managerId:_managerId]) { updateDelegate(); diff --git a/Telegram/SourceFiles/platform/mac/specific_mac.h b/Telegram/SourceFiles/platform/mac/specific_mac.h index 79be3067a..c8d7b598a 100644 --- a/Telegram/SourceFiles/platform/mac/specific_mac.h +++ b/Telegram/SourceFiles/platform/mac/specific_mac.h @@ -64,7 +64,7 @@ TimeMs psIdleTime(); QStringList psInitLogs(); void psClearInitLogs(); -void psActivateProcess(uint64 pid = 0); +void psActivateProcess(uint64_t pid = 0); QString psLocalServerPrefix(); QString psAppDataPath(); QString psDownloadPath(); diff --git a/Telegram/SourceFiles/platform/mac/specific_mac.mm b/Telegram/SourceFiles/platform/mac/specific_mac.mm index a801af673..d72e1a169 100644 --- a/Telegram/SourceFiles/platform/mac/specific_mac.mm +++ b/Telegram/SourceFiles/platform/mac/specific_mac.mm @@ -15,6 +15,7 @@ GNU General Public License for more details. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/mac/specific_mac.h" #include @@ -134,7 +135,7 @@ QString escapeShell(const QString &str) { return result; } -QStringList atosstr(uint64 *addresses, int count, uint64 base) { +QStringList atosstr(uint64_t *addresses, int count, uint64_t base) { QStringList result; if (!count || cExeName().isEmpty()) return result; @@ -178,10 +179,10 @@ QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { QString initial = QString::fromUtf8(crashdump), result; QStringList lines = initial.split('\n'); result.reserve(initial.size()); - int32 i = 0, l = lines.size(); + int32_t i = 0, l = lines.size(); while (i < l) { - uint64 addresses[1024] = { 0 }; + uint64_t addresses[1024] = { 0 }; for (; i < l; ++i) { result.append(lines.at(i)).append('\n'); QString line = lines.at(i).trimmed(); @@ -191,15 +192,15 @@ QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { } } - uint64 base = 0; - for (int32 start = i; i < l; ++i) { + uint64_t base = 0; + for (int32_t start = i; i < l; ++i) { QString line = lines.at(i).trimmed(); if (line.isEmpty()) break; if (!base) { QRegularExpressionMatch m = QRegularExpression(qsl("^\\d+ (\\d+) \\((.+)\\)")).match(line); if (m.hasMatch()) { - if (uint64 address = m.captured(1).toULongLong()) { + if (uint64_t address = m.captured(1).toULongLong()) { if (m.captured(2).endsWith(qstr("Contents/MacOS/Telegram"))) { base = address; } @@ -222,7 +223,7 @@ QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { } } - int32 start = i; + int32_t start = i; for (; i < l; ++i) { QString line = lines.at(i).trimmed(); if (line.isEmpty()) break; @@ -230,7 +231,7 @@ QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { if (QRegularExpression(qsl("^\\d+")).match(line).hasMatch()) { QStringList lst = line.split(' ', QString::SkipEmptyParts); if (lst.size() > 2) { - uint64 addr = lst.at(2).startsWith(qstr("0x")) ? lst.at(2).mid(2).toULongLong(0, 16) : lst.at(2).toULongLong(); + uint64_t addr = lst.at(2).startsWith(qstr("0x")) ? lst.at(2).mid(2).toULongLong(0, 16) : lst.at(2).toULongLong(); addresses[i - start] = addr; } } @@ -326,7 +327,7 @@ void psClearInitLogs() { _initLogs = QStringList(); } -void psActivateProcess(uint64 pid) { +void psActivateProcess(uint64_t pid) { if (!pid) { objc_activateProgram(App::wnd() ? App::wnd()->winId() : 0); } @@ -449,21 +450,21 @@ bool psLaunchMaps(const LocationCoords &coords) { } QString strNotificationAboutThemeChange() { - const uint32 letters[] = { 0xE9005541, 0x5600DC70, 0x88001570, 0xF500D86C, 0x8100E165, 0xEE005949, 0x2900526E, 0xAE00FB74, 0x96000865, 0x7000CD72, 0x3B001566, 0x5F007361, 0xAE00B663, 0x74009A65, 0x29003054, 0xC6002668, 0x98003865, 0xFA00336D, 0xA3007A65, 0x93001443, 0xBB007868, 0xE100E561, 0x3500366E, 0xC0007A67, 0x0200CA65, 0xBE00DF64, 0xE300BB4E, 0x2900D26F, 0xD500D374, 0xE900E269, 0x86008F66, 0xC4006669, 0x1C00A863, 0xE600A761, 0x8E00EE74, 0xB300B169, 0xCF00B36F, 0xE600D36E }; + const uint32_t letters[] = { 0xE9005541, 0x5600DC70, 0x88001570, 0xF500D86C, 0x8100E165, 0xEE005949, 0x2900526E, 0xAE00FB74, 0x96000865, 0x7000CD72, 0x3B001566, 0x5F007361, 0xAE00B663, 0x74009A65, 0x29003054, 0xC6002668, 0x98003865, 0xFA00336D, 0xA3007A65, 0x93001443, 0xBB007868, 0xE100E561, 0x3500366E, 0xC0007A67, 0x0200CA65, 0xBE00DF64, 0xE300BB4E, 0x2900D26F, 0xD500D374, 0xE900E269, 0x86008F66, 0xC4006669, 0x1C00A863, 0xE600A761, 0x8E00EE74, 0xB300B169, 0xCF00B36F, 0xE600D36E }; return strMakeFromLetters(letters); } QString strNotificationAboutScreenLocked() { - const uint32 letters[] = { 0x22008263, 0x0800DB6F, 0x45004F6D, 0xCC00972E, 0x0E00A861, 0x9700D970, 0xA100D570, 0x8900686C, 0xB300B365, 0xFE00DE2E, 0x76009B73, 0xFA00BF63, 0xE000A772, 0x9C009F65, 0x4E006065, 0xD900426E, 0xB7007849, 0x64006473, 0x6700824C, 0xE300706F, 0x7C00A063, 0x8F00D76B, 0x04001C65, 0x1C00A664 }; + const uint32_t letters[] = { 0x22008263, 0x0800DB6F, 0x45004F6D, 0xCC00972E, 0x0E00A861, 0x9700D970, 0xA100D570, 0x8900686C, 0xB300B365, 0xFE00DE2E, 0x76009B73, 0xFA00BF63, 0xE000A772, 0x9C009F65, 0x4E006065, 0xD900426E, 0xB7007849, 0x64006473, 0x6700824C, 0xE300706F, 0x7C00A063, 0x8F00D76B, 0x04001C65, 0x1C00A664 }; return strMakeFromLetters(letters); } QString strNotificationAboutScreenUnlocked() { - const uint32 letters[] = { 0x9200D763, 0xC8003C6F, 0xD2003F6D, 0x6000012E, 0x36004061, 0x4400E570, 0xA500BF70, 0x2E00796C, 0x4A009E65, 0x2E00612E, 0xC8001D73, 0x57002263, 0xF0005872, 0x49000765, 0xE5008D65, 0xE600D76E, 0xE8007049, 0x19005C73, 0x34009455, 0xB800B36E, 0xF300CA6C, 0x4C00806F, 0x5300A763, 0xD1003B6B, 0x63003565, 0xF800F264 }; + const uint32_t letters[] = { 0x9200D763, 0xC8003C6F, 0xD2003F6D, 0x6000012E, 0x36004061, 0x4400E570, 0xA500BF70, 0x2E00796C, 0x4A009E65, 0x2E00612E, 0xC8001D73, 0x57002263, 0xF0005872, 0x49000765, 0xE5008D65, 0xE600D76E, 0xE8007049, 0x19005C73, 0x34009455, 0xB800B36E, 0xF300CA6C, 0x4C00806F, 0x5300A763, 0xD1003B6B, 0x63003565, 0xF800F264 }; return strMakeFromLetters(letters); } QString strStyleOfInterface() { - const uint32 letters[] = { 0xEF004041, 0x4C007F70, 0x1F007A70, 0x9E00A76C, 0x8500D165, 0x2E003749, 0x7B00526E, 0x3400E774, 0x3C00FA65, 0x6200B172, 0xF7001D66, 0x0B002961, 0x71008C63, 0x86005465, 0xA3006F53, 0x11006174, 0xCD001779, 0x8200556C, 0x6C009B65 }; + const uint32_t letters[] = { 0xEF004041, 0x4C007F70, 0x1F007A70, 0x9E00A76C, 0x8500D165, 0x2E003749, 0x7B00526E, 0x3400E774, 0x3C00FA65, 0x6200B172, 0xF7001D66, 0x0B002961, 0x71008C63, 0x86005465, 0xA3006F53, 0x11006174, 0xCD001779, 0x8200556C, 0x6C009B65 }; return strMakeFromLetters(letters); } diff --git a/Telegram/SourceFiles/platform/mac/specific_mac_p.mm b/Telegram/SourceFiles/platform/mac/specific_mac_p.mm index 422add55f..1907d97b7 100644 --- a/Telegram/SourceFiles/platform/mac/specific_mac_p.mm +++ b/Telegram/SourceFiles/platform/mac/specific_mac_p.mm @@ -15,6 +15,7 @@ GNU General Public License for more details. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/mac/specific_mac_p.h" #include "mainwindow.h" @@ -176,7 +177,7 @@ ApplicationDelegate *_sharedDelegate = nil; } - (void) mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)e { - if (e && [e type] == NSSystemDefined && [e subtype] == SPSystemDefinedEventMediaKeys) { + if (e && [e type] == NSEventTypeSystemDefined && [e subtype] == SPSystemDefinedEventMediaKeys) { objc_handleMediaKeyEvent(e); } } @@ -255,7 +256,7 @@ void objc_showOverAll(WId winId, bool canFocus) { NSWindow *wnd = [reinterpret_cast(winId) window]; [wnd setLevel:NSPopUpMenuWindowLevel]; if (!canFocus) { - [wnd setStyleMask:NSUtilityWindowMask | NSNonactivatingPanelMask]; + [wnd setStyleMask:NSWindowStyleMaskUtilityWindow | NSWindowStyleMaskNonactivatingPanel]; [wnd setCollectionBehavior:NSWindowCollectionBehaviorMoveToActiveSpace|NSWindowCollectionBehaviorStationary|NSWindowCollectionBehaviorFullScreenAuxiliary|NSWindowCollectionBehaviorIgnoresCycle]; } } @@ -346,7 +347,7 @@ bool objc_idleTime(TimeMs &idleTime) { // taken from https://github.com/trueinte return false; } - uint64 err = ~0L, result = err; + uint64_t err = ~0L, result = err; if (obj) { CFTypeID type = CFGetTypeID(obj); diff --git a/Telegram/SourceFiles/platform/mac/window_title_mac.mm b/Telegram/SourceFiles/platform/mac/window_title_mac.mm index 0d5151e14..3e7ddaf52 100644 --- a/Telegram/SourceFiles/platform/mac/window_title_mac.mm +++ b/Telegram/SourceFiles/platform/mac/window_title_mac.mm @@ -18,6 +18,7 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/mac/window_title_mac.h" #include "mainwindow.h" diff --git a/Telegram/SourceFiles/platform/win/audio_win.cpp b/Telegram/SourceFiles/platform/win/audio_win.cpp index 1d9dfab40..41455768a 100644 --- a/Telegram/SourceFiles/platform/win/audio_win.cpp +++ b/Telegram/SourceFiles/platform/win/audio_win.cpp @@ -18,20 +18,20 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" + #include "platform/win/audio_win.h" #include "platform/win/windows_dlls.h" #include "media/media_audio.h" -#include -#include - -#include using namespace Microsoft::WRL; namespace Platform { namespace Audio { namespace { +const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); +const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); // Inspired by Chromium. class DeviceListener : public IMMNotificationClient { diff --git a/Telegram/SourceFiles/platform/win/file_utilities_win.cpp b/Telegram/SourceFiles/platform/win/file_utilities_win.cpp index bf0806351..d8959037c 100644 --- a/Telegram/SourceFiles/platform/win/file_utilities_win.cpp +++ b/Telegram/SourceFiles/platform/win/file_utilities_win.cpp @@ -18,6 +18,8 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" +#include #include "platform/win/file_utilities_win.h" #include "mainwindow.h" @@ -26,8 +28,6 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "lang/lang_keys.h" #include "messenger.h" -#include -#include HBITMAP qt_pixmapToWinHBITMAP(const QPixmap &, int hbitmapFormat); @@ -89,7 +89,7 @@ HBITMAP IconToBitmap(LPWSTR icon, int iconindex) { if (icon[0] == L'@' && SUCCEEDED(SHLoadIndirectString(icon, tmpIcon, 4096, 0))) { icon = tmpIcon; } - int32 w = GetSystemMetrics(SM_CXSMICON), h = GetSystemMetrics(SM_CYSMICON); + int32_t w = GetSystemMetrics(SM_CXSMICON), h = GetSystemMetrics(SM_CYSMICON); HICON ico = ExtractIcon(0, icon, iconindex); if (!ico) { @@ -184,7 +184,7 @@ bool UnsafeShowOpenWithDropdown(const QString &filepath, QPoint menuPosition) { std::sort(handlers.begin(), handlers.end(), [](const OpenWithApp &a, const OpenWithApp &b) { return a.name() < b.name(); }); - for (int32 i = 0, l = handlers.size(); i < l; ++i) { + for (int32_t i = 0, l = handlers.size(); i < l; ++i) { MENUITEMINFO menuInfo = { 0 }; menuInfo.cbSize = sizeof(menuInfo); menuInfo.fMask = MIIM_STRING | MIIM_DATA | MIIM_ID; @@ -319,9 +319,9 @@ void InitLastPath() { QList bookmarks; QStringList history; QString currentDirectory; - qint32 marker; - qint32 v; - qint32 viewMode; + int32_t marker; + int32_t v; + int32_t viewMode; stream >> marker; stream >> v; if (marker == _QFileDialogMagic && v == version) { @@ -420,9 +420,9 @@ bool Get(QStringList &files, QByteArray &remoteContent, const QString &caption, } else { files = dialog.selectedFiles().mid(0, 1); } - if (type == Type::ReadFile || type == Type::ReadFiles) { - remoteContent = dialog.selectedRemoteContent(); - } +// if (type == Type::ReadFile || type == Type::ReadFiles) { +// remoteContent = dialog.selectedRemoteContent(); +// } return true; } @@ -432,4 +432,4 @@ bool Get(QStringList &files, QByteArray &remoteContent, const QString &caption, } } // namespace FileDialog -} // namespace Platform \ No newline at end of file +} // namespace Platform diff --git a/Telegram/SourceFiles/platform/win/main_window_win.cpp b/Telegram/SourceFiles/platform/win/main_window_win.cpp index 33f6b5ae6..034400168 100644 --- a/Telegram/SourceFiles/platform/win/main_window_win.cpp +++ b/Telegram/SourceFiles/platform/win/main_window_win.cpp @@ -18,6 +18,7 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/win/main_window_win.h" #include "styles/style_window.h" @@ -34,17 +35,6 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include -#include -#include -#include - -#include -#include -#include -#include - -#include - #define min(a, b) ((a) < (b) ? (a) : (b)) #define max(a, b) ((a) < (b) ? (b) : (a)) #include @@ -106,7 +96,7 @@ enum { _PsInitVer = 0x02, }; -int32 _psSize = 0; +int32_t _psSize = 0; class _PsShadowWindows { public: @@ -155,13 +145,13 @@ public: _metaSize = _fullsize + 2 * _shift; _alphas.reserve(_metaSize); _colors.reserve(_metaSize * _metaSize); - for (int32 j = 0; j < _metaSize; ++j) { - for (int32 i = 0; i < _metaSize; ++i) { + for (int32_t j = 0; j < _metaSize; ++j) { + for (int32_t i = 0; i < _metaSize; ++i) { _colors.push_back((i < 2 * _shift || j < 2 * _shift) ? 1 : qMax(BYTE(1), BYTE(cornersImage.pixel(QPoint(i - 2 * _shift, j - 2 * _shift)) >> 24))); } } uchar prev = 0; - for (int32 i = 0; i < _metaSize; ++i) { + for (int32_t i = 0; i < _metaSize; ++i) { uchar a = _colors[(_metaSize - 1) * _metaSize + i]; if (a < prev) break; @@ -229,7 +219,7 @@ public: destroy(); return false; } - SetWindowLong(hwnds[i], GWL_HWNDPARENT, (LONG)hwnd); + SetWindowLong(hwnds[i], GWLP_HWNDPARENT, (LONG)hwnd); dcs[i] = CreateCompatibleDC(screenDC); if (!dcs[i]) { @@ -549,7 +539,7 @@ LRESULT CALLBACK _PsShadowWindows::wndProc(HWND hwnd, UINT msg, WPARAM wParam, L break; case WM_NCHITTEST: { - int32 xPos = GET_X_LPARAM(lParam), yPos = GET_Y_LPARAM(lParam); + int32_t xPos = GET_X_LPARAM(lParam), yPos = GET_Y_LPARAM(lParam); switch (i) { case 0: return HTTOP; case 1: return (yPos < _psShadowWindows._y + _psSize) ? HTTOPRIGHT : ((yPos >= _psShadowWindows._y + _psShadowWindows._h - _psSize) ? HTBOTTOMRIGHT : HTRIGHT); @@ -646,7 +636,7 @@ void MainWindow::psShowTrayMenu() { trayIconMenu->popup(QCursor::pos()); } -int32 MainWindow::screenNameChecksum(const QString &name) const { +int32_t MainWindow::screenNameChecksum(const QString &name) const { constexpr int DeviceNameSize = base::array_size(MONITORINFOEX().szDevice); wchar_t buffer[DeviceNameSize] = { 0 }; if (name.size() < DeviceNameSize) { @@ -705,18 +695,18 @@ void MainWindow::workmodeUpdated(DBIWorkMode mode) { switch (mode) { case dbiwmWindowAndTray: { psSetupTrayIcon(); - HWND psOwner = (HWND)GetWindowLong(ps_hWnd, GWL_HWNDPARENT); + HWND psOwner = (HWND)GetWindowLong(ps_hWnd, GWLP_HWNDPARENT); if (psOwner) { - SetWindowLong(ps_hWnd, GWL_HWNDPARENT, 0); + SetWindowLong(ps_hWnd, GWLP_HWNDPARENT, 0); psRefreshTaskbarIcon(); } } break; case dbiwmTrayOnly: { psSetupTrayIcon(); - HWND psOwner = (HWND)GetWindowLong(ps_hWnd, GWL_HWNDPARENT); + HWND psOwner = (HWND)GetWindowLong(ps_hWnd, GWLP_HWNDPARENT); if (!psOwner) { - SetWindowLong(ps_hWnd, GWL_HWNDPARENT, (LONG)ps_tbHider_hWnd); + SetWindowLong(ps_hWnd, GWLP_HWNDPARENT, (LONG)ps_tbHider_hWnd); } } break; @@ -727,9 +717,9 @@ void MainWindow::workmodeUpdated(DBIWorkMode mode) { } trayIcon = 0; - HWND psOwner = (HWND)GetWindowLong(ps_hWnd, GWL_HWNDPARENT); + HWND psOwner = (HWND)GetWindowLong(ps_hWnd, GWLP_HWNDPARENT); if (psOwner) { - SetWindowLong(ps_hWnd, GWL_HWNDPARENT, 0); + SetWindowLong(ps_hWnd, GWLP_HWNDPARENT, 0); psRefreshTaskbarIcon(); } } break; diff --git a/Telegram/SourceFiles/platform/win/main_window_win.h b/Telegram/SourceFiles/platform/win/main_window_win.h index 8951eb740..b4a69c1f6 100644 --- a/Telegram/SourceFiles/platform/win/main_window_win.h +++ b/Telegram/SourceFiles/platform/win/main_window_win.h @@ -85,7 +85,7 @@ public slots: protected: void initHook() override; - int32 screenNameChecksum(const QString &name) const override; + int32_t screenNameChecksum(const QString &name) const override; void unreadCounterChangedHook() override; void stateChangedHook(Qt::WindowState state) override; diff --git a/Telegram/SourceFiles/platform/win/notifications_manager_win.cpp b/Telegram/SourceFiles/platform/win/notifications_manager_win.cpp index 1c67bf299..0c4f0eb02 100644 --- a/Telegram/SourceFiles/platform/win/notifications_manager_win.cpp +++ b/Telegram/SourceFiles/platform/win/notifications_manager_win.cpp @@ -18,6 +18,7 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/win/notifications_manager_win.h" #include "window/notifications_utilities.h" @@ -27,14 +28,6 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "mainwindow.h" #include "base/task_queue.h" -#include -#include - -#include -#include -#include -#include - #include #include diff --git a/Telegram/SourceFiles/platform/win/specific_win.cpp b/Telegram/SourceFiles/platform/win/specific_win.cpp index 9d04deaaf..ef99a6b16 100644 --- a/Telegram/SourceFiles/platform/win/specific_win.cpp +++ b/Telegram/SourceFiles/platform/win/specific_win.cpp @@ -18,6 +18,7 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/win/specific_win.h" #include "platform/win/main_window_win.h" @@ -33,35 +34,14 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "passcodewidget.h" #include "base/task_queue.h" -#include -#include - -#include -#include -#include -#include - #pragma warning(push) #pragma warning(disable:4091) #include #include #pragma warning(pop) -#include -#include -#include -#include -#include - -#include -#include #include -#include -#include -#include -#include -#include #include @@ -125,15 +105,15 @@ void psDeleteDir(const QString &dir) { namespace { BOOL CALLBACK _ActivateProcess(HWND hWnd, LPARAM lParam) { - uint64 &processId(*(uint64*)lParam); + uint64_t &processId(*(uint64_t*)lParam); DWORD dwProcessId; ::GetWindowThreadProcessId(hWnd, &dwProcessId); - if ((uint64)dwProcessId == processId) { // found top-level window - static const int32 nameBufSize = 1024; + if ((uint64_t)dwProcessId == processId) { // found top-level window + static const int32_t nameBufSize = 1024; WCHAR nameBuf[nameBufSize]; - int32 len = GetWindowText(hWnd, nameBuf, nameBufSize); + int32_t len = GetWindowText(hWnd, nameBuf, nameBufSize); if (len && len < nameBufSize) { if (QRegularExpression(qsl("^Telegram(\\s*\\(\\d+\\))?$")).match(QString::fromStdWString(nameBuf)).hasMatch()) { BOOL res = ::SetForegroundWindow(hWnd); @@ -177,7 +157,7 @@ void psClearInitLogs() { _initLogs = QStringList(); } -void psActivateProcess(uint64 pid) { +void psActivateProcess(uint64_t pid) { if (pid) { ::EnumWindows((WNDENUMPROC)_ActivateProcess, (LPARAM)&pid); } @@ -1125,9 +1105,9 @@ QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { QString initial = QString::fromUtf8(crashdump), result; QStringList lines = initial.split('\n'); result.reserve(initial.size()); - int32 i = 0, l = lines.size(); + int32_t i = 0, l = lines.size(); QString versionstr; - uint64 version = 0, betaversion = 0; + uint64_t version = 0, betaversion = 0; for (; i < l; ++i) { result.append(lines.at(i)).append('\n'); QString line = lines.at(i).trimmed(); @@ -1153,7 +1133,7 @@ QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { QRegularExpressionMatch m = QRegularExpression("deploy/\\d+\\.\\d+/\\d+\\.\\d+\\.\\d+(/|\\.dev/|\\.alpha/|_\\d+/)(Telegram/)?$").match(path); if (m.hasMatch()) { QString base = path.mid(0, m.capturedStart()) + qstr("deploy/"); - int32 major = version / 1000000, minor = (version % 1000000) / 1000, micro = (version % 1000); + int32_t major = version / 1000000, minor = (version % 1000000) / 1000, micro = (version % 1000); base += qsl("%1.%2/%3.%4.%5").arg(major).arg(minor).arg(major).arg(minor).arg(micro); if (betaversion) { base += qsl("_%1").arg(betaversion); @@ -1198,7 +1178,7 @@ QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { Module.SizeOfStruct = sizeof(Module); StackEntry csEntry; - for (int32 start = i; i < l; ++i) { + for (int32_t start = i; i < l; ++i) { QString line = lines.at(i).trimmed(); if (line.isEmpty()) break; @@ -1264,7 +1244,7 @@ QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { result.append(csEntry.name).append(qsl(" (%1) 0x%3").arg(QString::fromWCharArray(csEntry.moduleName)).arg(address, 0, 16)).append('\n'); } else { QString file = QString::fromWCharArray(csEntry.lineFileName).toLower(); - int32 index = file.indexOf(qstr("tbuild\\tdesktop\\telegram\\")); + int32_t index = file.indexOf(qstr("tbuild\\tdesktop\\telegram\\")); if (index >= 0) { file = file.mid(index + qstr("tbuild\\tdesktop\\telegram\\").size()); if (file.startsWith(qstr("sourcefiles\\"))) { diff --git a/Telegram/SourceFiles/platform/win/specific_win.h b/Telegram/SourceFiles/platform/win/specific_win.h index 66de3d74d..fc2bedf53 100644 --- a/Telegram/SourceFiles/platform/win/specific_win.h +++ b/Telegram/SourceFiles/platform/win/specific_win.h @@ -75,7 +75,7 @@ TimeMs psIdleTime(); QStringList psInitLogs(); void psClearInitLogs(); -void psActivateProcess(uint64 pid = 0); +void psActivateProcess(uint64_t pid = 0); QString psLocalServerPrefix(); QString psAppDataPath(); QString psAppDataPathOld(); diff --git a/Telegram/SourceFiles/platform/win/window_title_win.cpp b/Telegram/SourceFiles/platform/win/window_title_win.cpp index 57d0bf200..51cd75d8c 100644 --- a/Telegram/SourceFiles/platform/win/window_title_win.cpp +++ b/Telegram/SourceFiles/platform/win/window_title_win.cpp @@ -18,6 +18,7 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/win/window_title_win.h" #include "ui/widgets/buttons.h" diff --git a/Telegram/SourceFiles/platform/win/windows_app_user_model_id.cpp b/Telegram/SourceFiles/platform/win/windows_app_user_model_id.cpp index 8eef2a47c..b208018a0 100644 --- a/Telegram/SourceFiles/platform/win/windows_app_user_model_id.cpp +++ b/Telegram/SourceFiles/platform/win/windows_app_user_model_id.cpp @@ -18,17 +18,13 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/win/windows_app_user_model_id.h" #include "platform/win/windows_dlls.h" #include #include -#include -#include -#include -#include - using namespace Microsoft::WRL; namespace Platform { diff --git a/Telegram/SourceFiles/platform/win/windows_dlls.cpp b/Telegram/SourceFiles/platform/win/windows_dlls.cpp index 2f6ffb272..44e0f4259 100644 --- a/Telegram/SourceFiles/platform/win/windows_dlls.cpp +++ b/Telegram/SourceFiles/platform/win/windows_dlls.cpp @@ -18,6 +18,7 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/win/windows_dlls.h" namespace Platform { diff --git a/Telegram/SourceFiles/platform/win/windows_dlls.h b/Telegram/SourceFiles/platform/win/windows_dlls.h index ae0c8b3c7..867bbc3cb 100644 --- a/Telegram/SourceFiles/platform/win/windows_dlls.h +++ b/Telegram/SourceFiles/platform/win/windows_dlls.h @@ -20,9 +20,6 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ #pragma once -#include -#include -#include namespace Platform { namespace Dlls { diff --git a/Telegram/SourceFiles/platform/win/windows_event_filter.cpp b/Telegram/SourceFiles/platform/win/windows_event_filter.cpp index a28f40b57..fc4d488df 100644 --- a/Telegram/SourceFiles/platform/win/windows_event_filter.cpp +++ b/Telegram/SourceFiles/platform/win/windows_event_filter.cpp @@ -18,6 +18,7 @@ to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ +#include "stdafx.h" #include "platform/win/windows_event_filter.h" #include "mainwindow.h" diff --git a/Telegram/SourceFiles/profile/profile_block_shared_media.cpp b/Telegram/SourceFiles/profile/profile_block_shared_media.cpp index ba852b470..2aa7a718c 100644 --- a/Telegram/SourceFiles/profile/profile_block_shared_media.cpp +++ b/Telegram/SourceFiles/profile/profile_block_shared_media.cpp @@ -43,15 +43,18 @@ QString getButtonText(MediaOverviewType type, int count) { case OverviewFiles: return lng_profile_files(lt_count, count); case OverviewVoiceFiles: return lng_profile_audios(lt_count, count); case OverviewLinks: return lng_profile_shared_links(lt_count, count); + case OverviewChatPhotos: case OverviewCount: return QString(); // temp } return QString(); } } // namespace -SharedMediaWidget::SharedMediaWidget(QWidget *parent, PeerData *peer) : BlockWidget(parent, peer, lang(lng_profile_shared_media)) -, _history(App::history(peer)) -, _migrated(_history->migrateFrom()) { +SharedMediaWidget::SharedMediaWidget(QWidget *parent, PeerData *peer) + : BlockWidget(parent, peer, lang(lng_profile_shared_media)) + , _history(App::history(peer)) + , _migrated(_history->migrateFrom()) +{ auto observeEvents = Notify::PeerUpdate::Flag::SharedMediaChanged | Notify::PeerUpdate::Flag::UserCommonChatsChanged; subscribe(Notify::PeerUpdated(), Notify::PeerUpdatedHandler(observeEvents, [this](const Notify::PeerUpdate &update) { diff --git a/Telegram/SourceFiles/profile/profile_common_groups_section.cpp b/Telegram/SourceFiles/profile/profile_common_groups_section.cpp index 25a9c7f2a..928d2618c 100644 --- a/Telegram/SourceFiles/profile/profile_common_groups_section.cpp +++ b/Telegram/SourceFiles/profile/profile_common_groups_section.cpp @@ -196,7 +196,7 @@ int InnerWidget::resizeGetHeight(int newWidth) { auto contentLeftMax = st::profileCommonGroupsLeftMax; auto widthWithMin = st::windowMinWidth; auto widthWithMax = st::profileCommonGroupsWidthMax + 2 * contentLeftMax; - _contentLeft = anim::interpolate(contentLeftMax, contentLeftMin, qMax(widthWithMax - newWidth, 0) / float64(widthWithMax - widthWithMin)); + _contentLeft = anim::interpolate(contentLeftMax, contentLeftMin, qMax(widthWithMax - newWidth, 0) / double(widthWithMax - widthWithMin)); _contentWidth = qMin(newWidth - 2 * _contentLeft, st::profileCommonGroupsWidthMax); auto newHeight = _contentTop; diff --git a/Telegram/SourceFiles/profile/profile_common_groups_section.h b/Telegram/SourceFiles/profile/profile_common_groups_section.h index a23a61488..7ca528bb8 100644 --- a/Telegram/SourceFiles/profile/profile_common_groups_section.h +++ b/Telegram/SourceFiles/profile/profile_common_groups_section.h @@ -161,7 +161,7 @@ private: int _selected = -1; int _pressed = -1; - int32 _preloadGroupId = 0; + int32_t _preloadGroupId = 0; mtpRequestId _preloadRequestId = 0; bool _allLoaded = true; diff --git a/Telegram/SourceFiles/qt_functions.cpp b/Telegram/SourceFiles/qt_functions.cpp new file mode 100644 index 000000000..e9875037c --- /dev/null +++ b/Telegram/SourceFiles/qt_functions.cpp @@ -0,0 +1,96 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file contains some parts of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL21$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 or version 3 as published by the Free +** Software Foundation and appearing in the file LICENSE.LGPLv21 and +** LICENSE.LGPLv3 included in the packaging of this file. Please review the +** following information to ensure the GNU Lesser General Public License +** requirements will be met: https://www.gnu.org/licenses/lgpl.html and +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** As a special exception, The Qt Company gives you certain additional +** rights. These rights are described in The Qt Company LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +/* TODO: find a dynamic library with these symbols. */ + +/* Debian maintainer: this function is taken from qfiledialog.cpp */ +/* + Makes a list of filters from ;;-separated text. + Used by the mac and windows implementations +*/ +QStringList qt_make_filter_list(const QString &filter) +{ + QString f(filter); + + if (f.isEmpty()) + return QStringList(); + + QString sep(QLatin1String(";;")); + int i = f.indexOf(sep, 0); + if (i == -1) { + if (f.indexOf(QLatin1Char('\n'), 0) != -1) { + sep = QLatin1Char('\n'); + i = f.indexOf(sep, 0); + } + } + + return f.split(sep); +} + +/* Debian maintainer: this constructor is taken from qtextengine.cpp for TextPainter::drawLine */ +QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe, const QTextCharFormat &format) + : flags(0), justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format), + num_chars(numChars), chars(chars_), logClusters(0), f(font), glyphs(g), fontEngine(fe) +{ +} + +/* Debian maintainer: this method is also taken from qtextengine.cpp */ +// Fix up flags and underlineStyle with given info +void QTextItemInt::initWithScriptItem(const QScriptItem &si) +{ + // explicitly initialize flags so that initFontAttributes can be called + // multiple times on the same TextItem + flags = 0; + if (si.analysis.bidiLevel %2) + flags |= QTextItem::RightToLeft; + ascent = si.ascent; + descent = si.descent; + + if (charFormat.hasProperty(QTextFormat::TextUnderlineStyle)) { + underlineStyle = charFormat.underlineStyle(); + } else if (charFormat.boolProperty(QTextFormat::FontUnderline) + || f->d->underline) { + underlineStyle = QTextCharFormat::SingleUnderline; + } + + // compat + if (underlineStyle == QTextCharFormat::SingleUnderline) + flags |= QTextItem::Underline; + + if (f->d->overline || charFormat.fontOverline()) + flags |= QTextItem::Overline; + if (f->d->strikeOut || charFormat.fontStrikeOut()) + flags |= QTextItem::StrikeOut; +} diff --git a/Telegram/SourceFiles/qt_static_plugins.cpp b/Telegram/SourceFiles/qt_static_plugins.cpp index b975c7a84..ae351018e 100644 --- a/Telegram/SourceFiles/qt_static_plugins.cpp +++ b/Telegram/SourceFiles/qt_static_plugins.cpp @@ -24,17 +24,8 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org Q_IMPORT_PLUGIN(QWebpPlugin) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin) #elif defined Q_OS_MAC // Q_OS_WIN -Q_IMPORT_PLUGIN(QWebpPlugin) -Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin) -Q_IMPORT_PLUGIN(QGenericEnginePlugin) +// Q_IMPORT_PLUGIN(QWebpPlugin) +// Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin) +// Q_IMPORT_PLUGIN(QGenericEnginePlugin) #elif defined Q_OS_LINUX // Q_OS_WIN | Q_OS_MAC -Q_IMPORT_PLUGIN(QWebpPlugin) -Q_IMPORT_PLUGIN(QXcbIntegrationPlugin) -Q_IMPORT_PLUGIN(QConnmanEnginePlugin) -Q_IMPORT_PLUGIN(QGenericEnginePlugin) -Q_IMPORT_PLUGIN(QNetworkManagerEnginePlugin) -Q_IMPORT_PLUGIN(QComposePlatformInputContextPlugin) -Q_IMPORT_PLUGIN(QIbusPlatformInputContextPlugin) -Q_IMPORT_PLUGIN(QFcitxPlatformInputContextPlugin) -Q_IMPORT_PLUGIN(QHimePlatformInputContextPlugin) #endif // Q_OS_WIN | Q_OS_MAC | Q_OS_LINUX diff --git a/Telegram/SourceFiles/settings.cpp b/Telegram/SourceFiles/settings.cpp index 4306551bd..2fca15de7 100644 --- a/Telegram/SourceFiles/settings.cpp +++ b/Telegram/SourceFiles/settings.cpp @@ -28,8 +28,8 @@ Qt::LayoutDirection gLangDir = gRtl ? Qt::RightToLeft : Qt::LeftToRight; QString gArguments; bool gAlphaVersion = AppAlphaVersion; -uint64 gBetaVersion = AppBetaVersion; -uint64 gRealBetaVersion = AppBetaVersion; +uint64_t gBetaVersion = AppBetaVersion; +uint64_t gRealBetaVersion = AppBetaVersion; QByteArray gBetaPrivateKey; bool gTestMode = false; @@ -54,14 +54,14 @@ LaunchMode gLaunchMode = LaunchModeNormal; bool gSupportTray = true; bool gSeenTrayTooltip = false; bool gRestartingUpdate = false, gRestarting = false, gRestartingToSettings = false, gWriteProtected = false; -int32 gLastUpdateCheck = 0; +int32_t gLastUpdateCheck = 0; bool gNoStartUpdate = false; bool gStartToSettings = false; bool gReplaceEmojis = true; bool gCtrlEnter = false; -uint32 gConnectionsInSession = 1; +uint32_t gConnectionsInSession = 1; QString gLoggedPhoneNumber; QByteArray gLocalSalt; @@ -85,12 +85,12 @@ RecentHashtagPack gRecentWriteHashtags, gRecentSearchHashtags; RecentInlineBots gRecentInlineBots; bool gPasswordRecovered = false; -int32 gPasscodeBadTries = 0; +int32_t gPasscodeBadTries = 0; TimeMs gPasscodeLastTry = 0; bool gRetina = false; -float64 gRetinaFactor = 1.; -int32 gIntRetinaFactor = 1; +double gRetinaFactor = 1.; +int32_t gIntRetinaFactor = 1; #ifdef Q_OS_WIN DBIPlatform gPlatform = dbipWindows; @@ -114,9 +114,9 @@ SavedPeersByTime gSavedPeersByTime; ReportSpamStatuses gReportSpamStatuses; -int32 gAutoDownloadPhoto = 0; // all auto download -int32 gAutoDownloadAudio = 0; -int32 gAutoDownloadGif = 0; +int32_t gAutoDownloadPhoto = 0; // all auto download +int32_t gAutoDownloadAudio = 0; +int32_t gAutoDownloadGif = 0; bool gAutoPlayGif = true; void ParseCommandLineArguments(const QStringList &arguments) { diff --git a/Telegram/SourceFiles/settings.h b/Telegram/SourceFiles/settings.h index e2de77ff3..12ff89724 100644 --- a/Telegram/SourceFiles/settings.h +++ b/Telegram/SourceFiles/settings.h @@ -20,6 +20,9 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ #pragma once +#include +#include + void InitFromCommandLine(int argc, char *argv[]); extern bool gDebug; @@ -58,8 +61,8 @@ inline bool rtl() { DeclareReadSetting(QString, Arguments); DeclareSetting(bool, AlphaVersion); -DeclareSetting(uint64, BetaVersion); -DeclareSetting(uint64, RealBetaVersion); +DeclareSetting(uint64_t, BetaVersion); +DeclareSetting(uint64_t, RealBetaVersion); DeclareSetting(QByteArray, BetaPrivateKey); DeclareSetting(bool, TestMode); @@ -100,7 +103,7 @@ DeclareSetting(bool, AutoUpdate); struct TWindowPos { TWindowPos() = default; - int32 moncrc = 0; + int32_t moncrc = 0; int maximized = 0; int x = 0; int y = 0; @@ -114,7 +117,7 @@ DeclareSetting(bool, RestartingUpdate); DeclareSetting(bool, Restarting); DeclareSetting(bool, RestartingToSettings); DeclareSetting(bool, WriteProtected); -DeclareSetting(int32, LastUpdateCheck); +DeclareSetting(int32_t, LastUpdateCheck); DeclareSetting(bool, NoStartUpdate); DeclareSetting(bool, StartToSettings); DeclareSetting(bool, ReplaceEmojis); @@ -141,9 +144,11 @@ inline DBIScale cScale() { template T convertScale(T v) { switch (cScale()) { - case dbisOneAndQuarter: return qRound(float64(v) * 1.25 - 0.01); - case dbisOneAndHalf: return qRound(float64(v) * 1.5 - 0.01); + case dbisOneAndQuarter: return qRound(double(v) * 1.25 - 0.01); + case dbisOneAndHalf: return qRound(double(v) * 1.5 - 0.01); case dbisTwo: return v * 2; + case dbisAuto: case dbisOne: return v; + case dbisScaleCount: assert(false); // temp } return v; } @@ -157,11 +162,11 @@ class One; using EmojiPtr = const Ui::Emoji::One*; using EmojiPack = QVector; -using RecentEmojiPreloadOldOld = QVector>; -using RecentEmojiPreloadOld = QVector>; -using RecentEmojiPreload = QVector>; -using RecentEmojiPack = QVector>; -using EmojiColorVariantsOld = QMap; +using RecentEmojiPreloadOldOld = QVector>; +using RecentEmojiPreloadOld = QVector>; +using RecentEmojiPreload = QVector>; +using RecentEmojiPack = QVector>; +using EmojiColorVariantsOld = QMap; using EmojiColorVariants = QMap; DeclareRefSetting(RecentEmojiPack, RecentEmoji); DeclareSetting(RecentEmojiPreload, RecentEmojiPreload); @@ -170,9 +175,9 @@ DeclareRefSetting(EmojiColorVariants, EmojiVariants); class DocumentData; typedef QVector StickerPack; -typedef QList > RecentStickerPackOld; -typedef QVector > RecentStickerPreload; -typedef QVector > RecentStickerPack; +typedef QList > RecentStickerPackOld; +typedef QVector > RecentStickerPreload; +typedef QVector > RecentStickerPack; DeclareSetting(RecentStickerPreload, RecentStickersPreload); DeclareRefSetting(RecentStickerPack, RecentStickers); @@ -184,7 +189,7 @@ typedef QVector SavedGifs; DeclareRefSetting(SavedGifs, SavedGifs); DeclareSetting(TimeMs, LastSavedGifsUpdate); -typedef QList > RecentHashtagPack; +typedef QList > RecentHashtagPack; DeclareRefSetting(RecentHashtagPack, RecentWriteHashtags); DeclareSetting(RecentHashtagPack, RecentSearchHashtags); @@ -194,7 +199,7 @@ DeclareRefSetting(RecentInlineBots, RecentInlineBots); DeclareSetting(bool, PasswordRecovered); -DeclareSetting(int32, PasscodeBadTries); +DeclareSetting(int32_t, PasscodeBadTries); DeclareSetting(TimeMs, PasscodeLastTry); inline bool passcodeCanTry() { @@ -249,8 +254,8 @@ DeclareSetting(QStringList, SendPaths); DeclareSetting(QString, StartUrl); DeclareSetting(bool, Retina); -DeclareSetting(float64, RetinaFactor); -DeclareSetting(int32, IntRetinaFactor); +DeclareSetting(double, RetinaFactor); +DeclareSetting(int32_t, IntRetinaFactor); DeclareReadSetting(DBIPlatform, Platform); DeclareReadSetting(QString, PlatformString); @@ -265,7 +270,7 @@ typedef QMultiMap SavedPeersByTime; DeclareRefSetting(SavedPeers, SavedPeers); DeclareRefSetting(SavedPeersByTime, SavedPeersByTime); -typedef QMap ReportSpamStatuses; +typedef QMap ReportSpamStatuses; DeclareRefSetting(ReportSpamStatuses, ReportSpamStatuses); enum DBIAutoDownloadFlags { @@ -273,9 +278,9 @@ enum DBIAutoDownloadFlags { dbiadNoGroups = 0x02, }; -DeclareSetting(int32, AutoDownloadPhoto); -DeclareSetting(int32, AutoDownloadAudio); -DeclareSetting(int32, AutoDownloadGif); +DeclareSetting(int32_t, AutoDownloadPhoto); +DeclareSetting(int32_t, AutoDownloadAudio); +DeclareSetting(int32_t, AutoDownloadGif); DeclareSetting(bool, AutoPlayGif); void settingsParseArgs(int argc, char *argv[]); diff --git a/Telegram/SourceFiles/settings/settings_background_widget.cpp b/Telegram/SourceFiles/settings/settings_background_widget.cpp index b9ea8150f..406b4ea38 100644 --- a/Telegram/SourceFiles/settings/settings_background_widget.cpp +++ b/Telegram/SourceFiles/settings/settings_background_widget.cpp @@ -71,7 +71,7 @@ void BackgroundRow::paintEvent(QPaintEvent *e) { Painter p(this); bool radial = false; - float64 radialOpacity = 0; + double radialOpacity = 0; if (_radial.animating()) { _radial.step(getms()); radial = _radial.animating(); @@ -126,7 +126,7 @@ int BackgroundRow::resizeGetHeight(int newWidth) { return st::settingsBackgroundSize; } -float64 BackgroundRow::radialProgress() const { +double BackgroundRow::radialProgress() const { if (auto m = App::main()) { return m->chatBackgroundProgress(); } @@ -172,7 +172,7 @@ void BackgroundRow::step_radial(TimeMs ms, bool timer) { } void BackgroundRow::updateImage() { - int32 size = st::settingsBackgroundSize * cIntRetinaFactor(); + int32_t size = st::settingsBackgroundSize * cIntRetinaFactor(); QImage back(size, size, QImage::Format_ARGB32_Premultiplied); back.setDevicePixelRatio(cRetinaFactor()); { diff --git a/Telegram/SourceFiles/settings/settings_background_widget.h b/Telegram/SourceFiles/settings/settings_background_widget.h index 93fb5091f..240eea491 100644 --- a/Telegram/SourceFiles/settings/settings_background_widget.h +++ b/Telegram/SourceFiles/settings/settings_background_widget.h @@ -47,7 +47,7 @@ signals: private: void checkNonDefaultTheme(); - float64 radialProgress() const; + double radialProgress() const; bool radialLoading() const; QRect radialRect() const; void radialStart(); diff --git a/Telegram/SourceFiles/settings/settings_chat_settings_widget.cpp b/Telegram/SourceFiles/settings/settings_chat_settings_widget.cpp index b6124ba7a..264e07a51 100644 --- a/Telegram/SourceFiles/settings/settings_chat_settings_widget.cpp +++ b/Telegram/SourceFiles/settings/settings_chat_settings_widget.cpp @@ -91,6 +91,7 @@ void DownloadPathState::paintEvent(QPaintEvent *e) { case State::Clearing: return lang(lng_download_path_clearing); case State::Cleared: return lang(lng_download_path_cleared); case State::ClearFailed: return lang(lng_download_path_clear_failed); + case State::Empty: case State::Exists: assert(false); // temp } return QString(); })(); diff --git a/Telegram/SourceFiles/settings/settings_general_widget.cpp b/Telegram/SourceFiles/settings/settings_general_widget.cpp index 38fe46a1b..7410ed04c 100644 --- a/Telegram/SourceFiles/settings/settings_general_widget.cpp +++ b/Telegram/SourceFiles/settings/settings_general_widget.cpp @@ -36,127 +36,9 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #include "lang/lang_file_parser.h" #include "lang/lang_cloud_manager.h" #include "messenger.h" -#include "autoupdater.h" namespace Settings { -#ifndef TDESKTOP_DISABLE_AUTOUPDATE -UpdateStateRow::UpdateStateRow(QWidget *parent) : TWidget(parent) -, _check(this, lang(lng_settings_check_now)) -, _restart(this, lang(lng_settings_update_now)) { - connect(_check, SIGNAL(clicked()), this, SLOT(onCheck())); - connect(_restart, SIGNAL(clicked()), this, SIGNAL(restart())); - - Sandbox::connect(SIGNAL(updateChecking()), this, SLOT(onChecking())); - Sandbox::connect(SIGNAL(updateLatest()), this, SLOT(onLatest())); - Sandbox::connect(SIGNAL(updateProgress(qint64, qint64)), this, SLOT(onDownloading(qint64, qint64))); - Sandbox::connect(SIGNAL(updateFailed()), this, SLOT(onFailed())); - Sandbox::connect(SIGNAL(updateReady()), this, SLOT(onReady())); - - _versionText = lng_settings_current_version_label(lt_version, currentVersionText()); - - switch (Sandbox::updatingState()) { - case Application::UpdatingDownload: - setState(State::Download, true); - setDownloadProgress(Sandbox::updatingReady(), Sandbox::updatingSize()); - break; - case Application::UpdatingReady: setState(State::Ready, true); break; - default: setState(State::None, true); break; - } -} - -int UpdateStateRow::resizeGetHeight(int newWidth) { - auto labelWidth = [](const QString &label) { - return st::linkFont->width(label) + st::linkFont->spacew; - }; - auto checkLeft = (_state == State::Latest) ? labelWidth(lang(lng_settings_latest_installed)) : labelWidth(_versionText); - auto restartLeft = labelWidth(lang(lng_settings_update_ready)); - - _check->resizeToWidth(qMin(newWidth, _check->naturalWidth())); - _check->moveToLeft(checkLeft, 0, newWidth); - - _restart->resizeToWidth(qMin(newWidth, _restart->naturalWidth())); - _restart->moveToLeft(restartLeft, 0, newWidth); - - return _check->height(); -} - -void UpdateStateRow::paintEvent(QPaintEvent *e) { - Painter p(this); - - auto text = ([this]() -> QString { - switch (_state) { - case State::Check: return lang(lng_settings_update_checking); - case State::Latest: return lang(lng_settings_latest_installed); - case State::Download: return _downloadText; - case State::Ready: return lang(lng_settings_update_ready); - case State::Fail: return lang(lng_settings_update_fail); - default: return _versionText; - } - })(); - p.setFont(st::linkFont); - p.setPen((_state == State::None) ? st::windowFg : st::settingsUpdateFg); - p.drawTextLeft(0, 0, width(), text); -} - -void UpdateStateRow::onCheck() { - if (!cAutoUpdate()) return; - - setState(State::Check); - cSetLastUpdateCheck(0); - Sandbox::startUpdateCheck(); -} - -void UpdateStateRow::setState(State state, bool force) { - if (_state != state || force) { - _state = state; - switch (state) { - case State::None: _check->show(); _restart->hide(); break; - case State::Ready: _check->hide(); _restart->show(); break; - case State::Check: - case State::Download: - case State::Latest: - case State::Fail: _check->hide(); _restart->hide(); break; - } - resizeToWidth(width()); - sendSynteticMouseEvent(this, QEvent::MouseMove, Qt::NoButton); - update(); - } -} - -void UpdateStateRow::setDownloadProgress(qint64 ready, qint64 total) { - auto readyTenthMb = (ready * 10 / (1024 * 1024)), totalTenthMb = (total * 10 / (1024 * 1024)); - auto readyStr = QString::number(readyTenthMb / 10) + '.' + QString::number(readyTenthMb % 10); - auto totalStr = QString::number(totalTenthMb / 10) + '.' + QString::number(totalTenthMb % 10); - auto result = lng_settings_downloading(lt_ready, readyStr, lt_total, totalStr); - if (_downloadText != result) { - _downloadText = result; - update(); - } -} - -void UpdateStateRow::onChecking() { - setState(State::Check); -} - -void UpdateStateRow::onLatest() { - setState(State::Latest); -} - -void UpdateStateRow::onDownloading(qint64 ready, qint64 total) { - setState(State::Download); - setDownloadProgress(ready, total); -} - -void UpdateStateRow::onReady() { - setState(State::Ready); -} - -void UpdateStateRow::onFailed() { - setState(State::Fail); -} -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - GeneralWidget::GeneralWidget(QWidget *parent, UserData *self) : BlockWidget(parent, self, lang(lng_settings_section_general)) , _changeLanguage(this, lang(lng_settings_change_lang), st::boxLinkButton) { connect(_changeLanguage, SIGNAL(clicked()), this, SLOT(onChangeLanguage())); @@ -174,16 +56,6 @@ void GeneralWidget::refreshControls() { style::margins marginSmall(0, 0, 0, st::settingsSmallSkip); style::margins slidedPadding(0, marginSmall.bottom() / 2, 0, marginSmall.bottom() - (marginSmall.bottom() / 2)); -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - addChildRow(_updateAutomatically, marginSub, lang(lng_settings_update_automatically), [this](bool) { onUpdateAutomatically(); }, cAutoUpdate()); - style::margins marginLink(st::defaultCheck.diameter + st::defaultBoxCheckbox.textPosition.x(), 0, 0, st::settingsSkip); - addChildRow(_updateRow, marginLink, slidedPadding); - connect(_updateRow->entity(), SIGNAL(restart()), this, SLOT(onRestart())); - if (!cAutoUpdate()) { - _updateRow->hideFast(); - } -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - if (cPlatform() == dbipWindows || cSupportTray()) { auto workMode = Global::WorkMode().value(); addChildRow(_enableTrayIcon, marginSmall, lang(lng_settings_workmode_tray), [this](bool) { onEnableTrayIcon(); }, (workMode == dbiwmTrayOnly || workMode == dbiwmWindowAndTray)); @@ -224,25 +96,9 @@ void GeneralWidget::onChangeLanguage() { } void GeneralWidget::onRestart() { -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - checkReadyUpdate(); -#endif // !TDESKTOP_DISABLE_AUTOUPDATE App::restart(); } -#ifndef TDESKTOP_DISABLE_AUTOUPDATE -void GeneralWidget::onUpdateAutomatically() { - cSetAutoUpdate(_updateAutomatically->checked()); - Local::writeSettings(); - _updateRow->toggleAnimated(cAutoUpdate()); - if (cAutoUpdate()) { - Sandbox::startUpdateCheck(); - } else { - Sandbox::stopUpdate(); - } -} -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - void GeneralWidget::onEnableTrayIcon() { if ((!_enableTrayIcon->checked() || cPlatform() != dbipWindows) && _enableTaskbarIcon && !_enableTaskbarIcon->checked()) { _enableTaskbarIcon->setChecked(true); diff --git a/Telegram/SourceFiles/settings/settings_general_widget.h b/Telegram/SourceFiles/settings/settings_general_widget.h index 71f2260a1..852e77c75 100644 --- a/Telegram/SourceFiles/settings/settings_general_widget.h +++ b/Telegram/SourceFiles/settings/settings_general_widget.h @@ -24,56 +24,6 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org namespace Settings { -#ifndef TDESKTOP_DISABLE_AUTOUPDATE -class UpdateStateRow : public TWidget { - Q_OBJECT - -public: - UpdateStateRow(QWidget *parent); - - bool isUpdateReady() const { - return (_state == State::Ready); - } - -protected: - int resizeGetHeight(int newWidth) override; - - void paintEvent(QPaintEvent *e) override; - -signals: - void restart(); - -private slots: - void onCheck(); - - void onChecking(); - void onLatest(); - void onDownloading(qint64 ready, qint64 total); - void onReady(); - void onFailed(); - -private: - enum class State { - None, - Check, - Latest, - Download, - Fail, - Ready - }; - void setState(State state, bool force = false); - void setDownloadProgress(qint64 ready, qint64 total); - - object_ptr _check; - object_ptr _restart; - - State _state = State::None; - QString _downloadText; - QString _versionText; - -}; -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - class GeneralWidget : public BlockWidget { Q_OBJECT @@ -86,10 +36,6 @@ protected: private slots: void onChangeLanguage(); -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - void onUpdateAutomatically(); -#endif // !TDESKTOP_DISABLE_AUTOUPDATE - void onEnableTrayIcon(); void onEnableTaskbarIcon(); @@ -106,10 +52,6 @@ private: void updateWorkmode(); object_ptr _changeLanguage; -#ifndef TDESKTOP_DISABLE_AUTOUPDATE - object_ptr _updateAutomatically = { nullptr }; - object_ptr> _updateRow = { nullptr }; -#endif // !TDESKTOP_DISABLE_AUTOUPDATE object_ptr _enableTrayIcon = { nullptr }; object_ptr _enableTaskbarIcon = { nullptr }; object_ptr _autoStart = { nullptr }; diff --git a/Telegram/SourceFiles/settings/settings_scale_widget.cpp b/Telegram/SourceFiles/settings/settings_scale_widget.cpp index 698b76e7a..8cac93601 100644 --- a/Telegram/SourceFiles/settings/settings_scale_widget.cpp +++ b/Telegram/SourceFiles/settings/settings_scale_widget.cpp @@ -39,6 +39,7 @@ QString scaleLabel(DBIScale scale) { case dbisOneAndQuarter: return qsl("125%"); case dbisOneAndHalf: return qsl("150%"); case dbisTwo: return qsl("200%"); + case dbisAuto: case dbisScaleCount: assert(false); // temp } return QString(); } @@ -74,6 +75,7 @@ void ScaleWidget::onAutoChanged() { case dbisOneAndQuarter: newScale = dbisOne; break; case dbisOneAndHalf: newScale = dbisOneAndQuarter; break; case dbisTwo: newScale = dbisOneAndHalf; break; + case dbisAuto: case dbisScaleCount: assert(false); // temp } } } diff --git a/Telegram/SourceFiles/stdafx.h b/Telegram/SourceFiles/stdafx.h index 9c1d5f5e3..f39f36f65 100644 --- a/Telegram/SourceFiles/stdafx.h +++ b/Telegram/SourceFiles/stdafx.h @@ -53,6 +53,36 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org #define MAC_USE_BREAKPAD #endif // OS_MAC_STORE +#ifdef Q_OS_WIN +#include + +// Windows Header Files: +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#endif + #include #include diff --git a/Telegram/SourceFiles/storage/file_download.cpp b/Telegram/SourceFiles/storage/file_download.cpp index 3b82ee890..607980b88 100644 --- a/Telegram/SourceFiles/storage/file_download.cpp +++ b/Telegram/SourceFiles/storage/file_download.cpp @@ -99,7 +99,7 @@ struct FileLoaderQueue { namespace { -using LoaderQueues = QMap; +using LoaderQueues = QMap; LoaderQueues queues; FileLoaderQueue _webQueue(kMaxWebFileQueries); @@ -113,7 +113,7 @@ WebLoadMainManager *_webLoadMainManager = nullptr; } // namespace -FileLoader::FileLoader(const QString &toFile, int32 size, LocationType locationType, LoadToCacheSetting toCache, LoadFromCloudSetting fromCloud, bool autoLoading) +FileLoader::FileLoader(const QString &toFile, int32_t size, LocationType locationType, LoadToCacheSetting toCache, LoadFromCloudSetting fromCloud, bool autoLoading) : _downloader(&Auth().downloader()) , _autoLoading(autoLoading) , _filename(toFile) @@ -152,13 +152,13 @@ void FileLoader::readImage(const QSize &shrinkBox) const { } } -float64 FileLoader::currentProgress() const { +double FileLoader::currentProgress() const { if (_finished) return 1.; if (!fullSize()) return 0.; - return snap(float64(currentOffset()) / fullSize(), 0., 1.); + return snap(double(currentOffset()) / fullSize(), 0., 1.); } -int32 FileLoader::fullSize() const { +int32_t FileLoader::fullSize() const { return _size; } @@ -239,7 +239,7 @@ void FileLoader::localLoaded(const StorageImageSaved &result, const QByteArray & cancel(true); return; } - if (_file.write(_data) != qint64(_data.size())) { + if (_file.write(_data) != int64_t(_data.size())) { cancel(true); return; } @@ -400,7 +400,7 @@ void FileLoader::startLoading(bool loadFirst, bool prior) { loadPart(); } -mtpFileLoader::mtpFileLoader(const StorageImageLocation *location, int32 size, LoadFromCloudSetting fromCloud, bool autoLoading) +mtpFileLoader::mtpFileLoader(const StorageImageLocation *location, int32_t size, LoadFromCloudSetting fromCloud, bool autoLoading) : FileLoader(QString(), size, UnknownFileLocation, LoadToCacheAsWell, fromCloud, autoLoading) , _dcId(location->dc()) , _location(location) { @@ -412,7 +412,7 @@ mtpFileLoader::mtpFileLoader(const StorageImageLocation *location, int32 size, L _queue = &i.value(); } -mtpFileLoader::mtpFileLoader(int32 dc, uint64 id, uint64 accessHash, int32 version, LocationType type, const QString &to, int32 size, LoadToCacheSetting toCache, LoadFromCloudSetting fromCloud, bool autoLoading) +mtpFileLoader::mtpFileLoader(int32_t dc, uint64_t id, uint64_t accessHash, int32_t version, LocationType type, const QString &to, int32_t size, LoadToCacheSetting toCache, LoadFromCloudSetting fromCloud, bool autoLoading) : FileLoader(to, size, type, toCache, fromCloud, autoLoading) , _dcId(dc) , _id(id) @@ -426,7 +426,7 @@ mtpFileLoader::mtpFileLoader(int32 dc, uint64 id, uint64 accessHash, int32 versi _queue = &i.value(); } -mtpFileLoader::mtpFileLoader(const WebFileImageLocation *location, int32 size, LoadFromCloudSetting fromCloud, bool autoLoading) +mtpFileLoader::mtpFileLoader(const WebFileImageLocation *location, int32_t size, LoadFromCloudSetting fromCloud, bool autoLoading) : FileLoader(QString(), size, UnknownFileLocation, LoadToCacheAsWell, fromCloud, autoLoading) , _dcId(location->dc()) , _urlLocation(location) { @@ -438,7 +438,7 @@ mtpFileLoader::mtpFileLoader(const WebFileImageLocation *location, int32 size, L _queue = &i.value(); } -int32 mtpFileLoader::currentOffset(bool includeSkipped) const { +int32_t mtpFileLoader::currentOffset(bool includeSkipped) const { return (_fileIsOpen ? _file.size() : _data.size()) - (includeSkipped ? 0 : _skippedBytes); } @@ -568,7 +568,7 @@ void mtpFileLoader::cdnPartLoaded(const MTPupload_CdnFile &result, mtpRequestId auto ivec = gsl::as_writeable_bytes(gsl::make_span(state.ivec)); std::copy(iv.begin(), iv.end(), ivec.begin()); - auto counterOffset = static_cast(offset) >> 4; + auto counterOffset = static_cast(offset) >> 4; state.ivec[15] = static_cast(counterOffset & 0xFF); state.ivec[14] = static_cast((counterOffset >> 8) & 0xFF); state.ivec[13] = static_cast((counterOffset >> 16) & 0xFF); @@ -689,7 +689,7 @@ void mtpFileLoader::partLoaded(int offset, base::const_byte_span bytes) { _skippedBytes += offset - fsize; } _file.seek(offset); - if (_file.write(reinterpret_cast(bytes.data()), bytes.size()) != qint64(bytes.size())) { + if (_file.write(reinterpret_cast(bytes.data()), bytes.size()) != int64_t(bytes.size())) { return cancel(true); } } else { @@ -712,7 +712,7 @@ void mtpFileLoader::partLoaded(int offset, base::const_byte_span bytes) { _data.append(reinterpret_cast(bytes.data()), bytes.size()); } else { _skippedBytes -= bytes.size(); - if (int64(offset + bytes.size()) > _data.size()) { + if (int64_t(offset + bytes.size()) > _data.size()) { _data.resize(offset + bytes.size()); } auto src = bytes; @@ -730,7 +730,7 @@ void mtpFileLoader::partLoaded(int offset, base::const_byte_span bytes) { if (!_fileIsOpen) { return cancel(true); } - if (_file.write(_data) != qint64(_data.size())) { + if (_file.write(_data) != int64_t(_data.size())) { return cancel(true); } } @@ -908,11 +908,11 @@ bool webFileLoader::loadPart() { return false; } -int32 webFileLoader::currentOffset(bool includeSkipped) const { +int32_t webFileLoader::currentOffset(bool includeSkipped) const { return _already; } -void webFileLoader::onProgress(qint64 already, qint64 size) { +void webFileLoader::onProgress(int64_t already, int64_t size) { _size = size; _already = already; @@ -921,7 +921,7 @@ void webFileLoader::onProgress(qint64 already, qint64 size) { void webFileLoader::onFinished(const QByteArray &data) { if (_fileIsOpen) { - if (_file.write(data.constData(), data.size()) != qint64(data.size())) { + if (_file.write(data.constData(), data.size()) != int64_t(data.size())) { return cancel(true); } } else { @@ -932,7 +932,7 @@ void webFileLoader::onFinished(const QByteArray &data) { if (!_fileIsOpen) { return cancel(true); } - if (_file.write(_data) != qint64(_data.size())) { + if (_file.write(_data) != int64_t(_data.size())) { return cancel(true); } } @@ -1024,15 +1024,15 @@ public: const QByteArray &data() { return _data; } - void setProgress(qint64 already, qint64 size) { + void setProgress(int64_t already, int64_t size) { _already = already; _size = qMax(size, 0LL); } - qint64 size() const { + int64_t size() const { return _size; } - qint64 already() const { + int64_t already() const { return _already; } @@ -1041,10 +1041,10 @@ private: webFileLoader *_interface = nullptr; QUrl _url; - qint64 _already = 0; - qint64 _size = 0; + int64_t _already = 0; + int64_t _size = 0; QNetworkReply *_reply = nullptr; - int32 _redirectsLeft = kMaxHttpRedirects; + int32_t _redirectsLeft = kMaxHttpRedirects; QByteArray _data; friend class WebLoadManager; @@ -1088,7 +1088,7 @@ WebLoadManager::WebLoadManager(QThread *thread) { connect(this, SIGNAL(processDelayed()), this, SLOT(process()), Qt::QueuedConnection); connect(this, SIGNAL(proxyApplyDelayed()), this, SLOT(proxyApply()), Qt::QueuedConnection); - connect(this, SIGNAL(progress(webFileLoader*,qint64,qint64)), _webLoadMainManager, SLOT(progress(webFileLoader*,qint64,qint64))); + connect(this, SIGNAL(progress(webFileLoader*,int64_t,int64_t)), _webLoadMainManager, SLOT(progress(webFileLoader*,int64_t,int64_t))); connect(this, SIGNAL(finished(webFileLoader*,QByteArray)), _webLoadMainManager, SLOT(finished(webFileLoader*,QByteArray))); connect(this, SIGNAL(error(webFileLoader*)), _webLoadMainManager, SLOT(error(webFileLoader*))); @@ -1170,7 +1170,7 @@ void WebLoadManager::onFailed(QNetworkReply *reply) { } } -void WebLoadManager::onProgress(qint64 already, qint64 size) { +void WebLoadManager::onProgress(int64_t already, int64_t size) { QNetworkReply *reply = qobject_cast(QObject::sender()); if (!reply) return; @@ -1182,7 +1182,7 @@ void WebLoadManager::onProgress(qint64 already, qint64 size) { WebReplyProcessResult result = WebReplyProcessProgress; QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); - int32 status = statusCode.isValid() ? statusCode.toInt() : 200; + int32_t status = statusCode.isValid() ? statusCode.toInt() : 200; if (status != 200 && status != 206 && status != 416) { if (status == 301 || status == 302) { QString loc = reply->header(QNetworkRequest::LocationHeader).toString(); @@ -1236,7 +1236,7 @@ void WebLoadManager::onMeta() { if (QString::fromUtf8(i->first).toLower() == "content-range") { QRegularExpressionMatch m = QRegularExpression(qsl("/(\\d+)([^\\d]|$)")).match(QString::fromUtf8(i->second)); if (m.hasMatch()) { - loader->setProgress(qMax(qint64(loader->data().size()), loader->already()), m.captured(1).toLongLong()); + loader->setProgress(qMax(int64_t(loader->data().size()), loader->already()), m.captured(1).toLongLong()); if (!handleReplyResult(loader, WebReplyProcessProgress)) { _replies.erase(j); _loaders.remove(loader); @@ -1300,7 +1300,7 @@ void WebLoadManager::sendRequest(webFileLoaderPrivate *loader, const QString &re } QNetworkReply *r = loader->request(_manager, redirect); - connect(r, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onProgress(qint64, qint64))); + connect(r, SIGNAL(downloadProgress(int64_t, int64_t)), this, SLOT(onProgress(int64_t, int64_t))); connect(r, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onFailed(QNetworkReply::NetworkError))); connect(r, SIGNAL(metaDataChanged()), this, SLOT(onMeta())); _replies.insert(r, loader); @@ -1341,7 +1341,7 @@ WebLoadManager::~WebLoadManager() { clear(); } -void WebLoadMainManager::progress(webFileLoader *loader, qint64 already, qint64 size) { +void WebLoadMainManager::progress(webFileLoader *loader, int64_t already, int64_t size) { if (webLoadManager() && webLoadManager()->carries(loader)) { loader->onProgress(already, size); } diff --git a/Telegram/SourceFiles/storage/file_download.h b/Telegram/SourceFiles/storage/file_download.h index 578513b2f..a0258427f 100644 --- a/Telegram/SourceFiles/storage/file_download.h +++ b/Telegram/SourceFiles/storage/file_download.h @@ -57,7 +57,7 @@ private: SingleQueuedInvokation _delayedLoadersDestroyer; std::vector> _delayedDestroyedLoaders; - using RequestedInDc = std::array; + using RequestedInDc = std::array; std::map _requestedBytesAmount; }; @@ -89,7 +89,7 @@ class FileLoader : public QObject { Q_OBJECT public: - FileLoader(const QString &toFile, int32 size, LocationType locationType, LoadToCacheSetting, LoadFromCloudSetting fromCloud, bool autoLoading); + FileLoader(const QString &toFile, int32_t size, LocationType locationType, LoadToCacheSetting, LoadFromCloudSetting fromCloud, bool autoLoading); bool finished() const { return _finished; } @@ -99,7 +99,7 @@ public: const QByteArray &bytes() const { return _data; } - virtual uint64 objId() const { + virtual uint64_t objId() const { return 0; } QByteArray imageFormat(const QSize &shrinkBox = QSize()) const; @@ -107,9 +107,9 @@ public: QString fileName() const { return _filename; } - float64 currentProgress() const; - virtual int32 currentOffset(bool includeSkipped = false) const = 0; - int32 fullSize() const; + double currentProgress() const; + virtual int32_t currentOffset(bool includeSkipped = false) const = 0; + int32_t fullSize() const; bool setFileName(const QString &filename); // set filename for loaders to cache void permitLoadFromCloud(); @@ -179,7 +179,7 @@ protected: QByteArray _data; - int32 _size; + int32_t _size; LocationType _locationType; TaskId _localTaskId = 0; @@ -194,13 +194,13 @@ class mtpFileLoader : public FileLoader, public RPCSender { Q_OBJECT public: - mtpFileLoader(const StorageImageLocation *location, int32 size, LoadFromCloudSetting fromCloud, bool autoLoading); - mtpFileLoader(int32 dc, uint64 id, uint64 accessHash, int32 version, LocationType type, const QString &toFile, int32 size, LoadToCacheSetting toCache, LoadFromCloudSetting fromCloud, bool autoLoading); - mtpFileLoader(const WebFileImageLocation *location, int32 size, LoadFromCloudSetting fromCloud, bool autoLoading); + mtpFileLoader(const StorageImageLocation *location, int32_t size, LoadFromCloudSetting fromCloud, bool autoLoading); + mtpFileLoader(int32_t dc, uint64_t id, uint64_t accessHash, int32_t version, LocationType type, const QString &toFile, int32_t size, LoadToCacheSetting toCache, LoadFromCloudSetting fromCloud, bool autoLoading); + mtpFileLoader(const WebFileImageLocation *location, int32_t size, LoadFromCloudSetting fromCloud, bool autoLoading); - int32 currentOffset(bool includeSkipped = false) const override; + int32_t currentOffset(bool includeSkipped = false) const override; - uint64 objId() const override { + uint64_t objId() const override { return _id; } @@ -258,15 +258,15 @@ private: std::map _sentRequests; bool _lastComplete = false; - int32 _skippedBytes = 0; - int32 _nextRequestOffset = 0; + int32_t _skippedBytes = 0; + int32_t _nextRequestOffset = 0; MTP::DcId _dcId = 0; // for photo locations const StorageImageLocation *_location = nullptr; - uint64 _id = 0; // for document locations - uint64 _accessHash = 0; - int32 _version = 0; + uint64_t _id = 0; // for document locations + uint64_t _accessHash = 0; + int32_t _version = 0; const WebFileImageLocation *_urlLocation = nullptr; // for webdocument locations @@ -289,7 +289,7 @@ public: webFileLoader(const QString &url, const QString &to, LoadFromCloudSetting fromCloud, bool autoLoading); - virtual int32 currentOffset(bool includeSkipped = false) const; + virtual int32_t currentOffset(bool includeSkipped = false) const; virtual webFileLoader *webLoader() { return this; } @@ -297,7 +297,7 @@ public: return this; } - void onProgress(qint64 already, qint64 size); + void onProgress(int64_t already, int64_t size); void onFinished(const QByteArray &data); void onError(); @@ -316,7 +316,7 @@ protected: QString _url; bool _requestSent; - int32 _already; + int32_t _already; friend class WebLoadManager; webFileLoaderPrivate *_private; @@ -349,14 +349,14 @@ signals: void processDelayed(); void proxyApplyDelayed(); - void progress(webFileLoader *loader, qint64 already, qint64 size); + void progress(webFileLoader *loader, int64_t already, int64_t size); void finished(webFileLoader *loader, QByteArray data); void error(webFileLoader *loader); public slots: void onFailed(QNetworkReply *reply); void onFailed(QNetworkReply::NetworkError error); - void onProgress(qint64 already, qint64 size); + void onProgress(int64_t already, int64_t size); void onMeta(); void process(); @@ -391,7 +391,7 @@ public: public slots: - void progress(webFileLoader *loader, qint64 already, qint64 size); + void progress(webFileLoader *loader, int64_t already, int64_t size); void finished(webFileLoader *loader, QByteArray data); void error(webFileLoader *loader); diff --git a/Telegram/SourceFiles/storage/file_upload.cpp b/Telegram/SourceFiles/storage/file_upload.cpp index e665a2403..25d392177 100644 --- a/Telegram/SourceFiles/storage/file_upload.cpp +++ b/Telegram/SourceFiles/storage/file_upload.cpp @@ -136,7 +136,7 @@ void Uploader::sendNext() { } UploadFileParts &parts(i->file ? (i->type() == SendMediaType::Photo ? i->file->fileparts : i->file->thumbparts) : i->media.parts); - uint64 partsOfId(i->file ? (i->type() == SendMediaType::Photo ? i->file->id : i->file->thumbId) : i->media.thumbId); + uint64_t partsOfId(i->file ? (i->type() == SendMediaType::Photo ? i->file->id : i->file->thumbId) : i->media.thumbId); if (parts.isEmpty()) { if (i->docSentParts >= i->docPartsCount) { if (requestsSent.isEmpty() && docRequestsSent.isEmpty()) { @@ -246,7 +246,7 @@ void Uploader::clear() { MTP::cancel(i.key()); } requestsSent.clear(); - for (QMap::const_iterator i = docRequestsSent.cbegin(), e = docRequestsSent.cend(); i != e; ++i) { + for (QMap::const_iterator i = docRequestsSent.cbegin(), e = docRequestsSent.cend(); i != e; ++i) { MTP::cancel(i.key()); } docRequestsSent.clear(); @@ -260,7 +260,7 @@ void Uploader::clear() { } void Uploader::partLoaded(const MTPBool &result, mtpRequestId requestId) { - QMap::iterator j = docRequestsSent.end(); + QMap::iterator j = docRequestsSent.end(); QMap::iterator i = requestsSent.find(requestId); if (i == requestsSent.cend()) { j = docRequestsSent.find(requestId); @@ -270,15 +270,15 @@ void Uploader::partLoaded(const MTPBool &result, mtpRequestId requestId) { currentFailed(); return; } else { - QMap::iterator dcIt = dcMap.find(requestId); + QMap::iterator dcIt = dcMap.find(requestId); if (dcIt == dcMap.cend()) { // must not happen currentFailed(); return; } - int32 dc = dcIt.value(); + int32_t dc = dcIt.value(); dcMap.erase(dcIt); - int32 sentPartSize = 0; + int32_t sentPartSize = 0; Queue::const_iterator k = queue.constFind(uploading); if (i != requestsSent.cend()) { sentPartSize = i.value().size(); diff --git a/Telegram/SourceFiles/storage/file_upload.h b/Telegram/SourceFiles/storage/file_upload.h index b510d655d..d4a8e3ae3 100644 --- a/Telegram/SourceFiles/storage/file_upload.h +++ b/Telegram/SourceFiles/storage/file_upload.h @@ -32,8 +32,8 @@ public: void uploadMedia(const FullMsgId &msgId, const SendMediaReady &image); void upload(const FullMsgId &msgId, const FileLoadResultPtr &file); - int32 currentOffset(const FullMsgId &msgId) const; // -1 means file not found - int32 fullSize(const FullMsgId &msgId) const; + int32_t currentOffset(const FullMsgId &msgId) const; // -1 means file not found + int32_t fullSize(const FullMsgId &msgId) const; void cancel(const FullMsgId &msgId); void pause(const FullMsgId &msgId); @@ -77,7 +77,7 @@ private: docSize = docPartSize = docPartsCount = 0; } } - void setDocSize(int32 size) { + void setDocSize(int32_t size) { docSize = size; if (docSize >= 1024 * 1024 || !setPartSize(DocumentUploadPartSize0)) { if (docSize > 32 * 1024 * 1024 || !setPartSize(DocumentUploadPartSize1)) { @@ -91,7 +91,7 @@ private: } } } - bool setPartSize(uint32 partSize) { + bool setPartSize(uint32_t partSize) { docPartSize = partSize; docPartsCount = (docSize / docPartSize) + ((docSize % docPartSize) ? 1 : 0); return (docPartsCount <= DocumentMaxPartsCount); @@ -99,16 +99,16 @@ private: FileLoadResultPtr file; SendMediaReady media; - int32 partsCount; - mutable int32 fileSentSize; + int32_t partsCount; + mutable int32_t fileSentSize; - uint64 id() const { + uint64_t id() const { return file ? file->id : media.id; } SendMediaType type() const { return file ? file->type : media.type; } - uint64 thumbId() const { + uint64_t thumbId() const { return file ? file->thumbId : media.thumbId; } const QString &filename() const { @@ -118,10 +118,10 @@ private: HashMd5 md5Hash; QSharedPointer docFile; - int32 docSentParts; - int32 docSize; - int32 docPartSize; - int32 docPartsCount; + int32_t docSentParts; + int32_t docSize; + int32_t docPartSize; + int32_t docPartsCount; }; typedef QMap Queue; @@ -131,10 +131,10 @@ private: void currentFailed(); QMap requestsSent; - QMap docRequestsSent; - QMap dcMap; - uint32 sentSize = 0; - uint32 sentSizes[MTP::kUploadSessionsCount] = { 0 }; + QMap docRequestsSent; + QMap dcMap; + uint32_t sentSize = 0; + uint32_t sentSizes[MTP::kUploadSessionsCount] = { 0 }; FullMsgId uploading, _paused; Queue queue; diff --git a/Telegram/SourceFiles/storage/localimageloader.cpp b/Telegram/SourceFiles/storage/localimageloader.cpp index 4a1e01340..7f07ecdb8 100644 --- a/Telegram/SourceFiles/storage/localimageloader.cpp +++ b/Telegram/SourceFiles/storage/localimageloader.cpp @@ -38,7 +38,7 @@ bool ValidateThumbDimensions(int width, int height) { } // namespace -TaskQueue::TaskQueue(QObject *parent, int32 stopTimeoutMs) : QObject(parent), _thread(0), _worker(0), _stopTimer(0) { +TaskQueue::TaskQueue(QObject *parent, int32_t stopTimeoutMs) : QObject(parent), _thread(0), _worker(0), _stopTimer(0) { if (stopTimeoutMs > 0) { _stopTimer = new QTimer(this); connect(_stopTimer, SIGNAL(timeout()), this, SLOT(stop())); @@ -86,7 +86,7 @@ void TaskQueue::wakeThread() { void TaskQueue::cancelTask(TaskId id) { { QMutexLocker lock(&_tasksToProcessMutex); - for (int32 i = 0, l = _tasksToProcess.size(); i != l; ++i) { + for (int32_t i = 0, l = _tasksToProcess.size(); i != l; ++i) { if (_tasksToProcess.at(i)->id() == id) { _tasksToProcess.removeAt(i); return; @@ -94,7 +94,7 @@ void TaskQueue::cancelTask(TaskId id) { } } QMutexLocker lock(&_tasksToFinishMutex); - for (int32 i = 0, l = _tasksToFinish.size(); i != l; ++i) { + for (int32_t i = 0, l = _tasksToFinish.size(); i != l; ++i) { if (_tasksToFinish.at(i)->id() == id) { _tasksToFinish.removeAt(i); return; @@ -180,7 +180,7 @@ void TaskQueueWorker::onTaskAdded() { _inTaskAdded = false; } -FileLoadTask::FileLoadTask(const QString &filepath, std::unique_ptr information, SendMediaType type, const FileLoadTo &to, const QString &caption) : _id(rand_value()) +FileLoadTask::FileLoadTask(const QString &filepath, std::unique_ptr information, SendMediaType type, const FileLoadTo &to, const QString &caption) : _id(rand_value()) , _to(to) , _filepath(filepath) , _information(std::move(information)) @@ -188,7 +188,7 @@ FileLoadTask::FileLoadTask(const QString &filepath, std::unique_ptr()) +FileLoadTask::FileLoadTask(const QByteArray &content, const QImage &image, SendMediaType type, const FileLoadTo &to, const QString &caption) : _id(rand_value()) , _to(to) , _content(content) , _image(image) @@ -196,7 +196,7 @@ FileLoadTask::FileLoadTask(const QByteArray &content, const QImage &image, SendM , _caption(caption) { } -FileLoadTask::FileLoadTask(const QByteArray &voice, int32 duration, const VoiceWaveform &waveform, const FileLoadTo &to, const QString &caption) : _id(rand_value()) +FileLoadTask::FileLoadTask(const QByteArray &voice, int32_t duration, const VoiceWaveform &waveform, const FileLoadTo &to, const QString &caption) : _id(rand_value()) , _to(to) , _content(voice) , _duration(duration) @@ -320,10 +320,10 @@ void FileLoadTask::process() { _result = MakeShared(_id, _to, _caption); QString filename, filemime; - qint64 filesize = 0; + int64_t filesize = 0; QByteArray filedata; - uint64 thumbId = 0; + uint64_t thumbId = 0; auto thumbname = qsl("thumb.jpg"); QByteArray thumbdata; @@ -410,7 +410,7 @@ void FileLoadTask::process() { fullimage = Images::prepareOpaque(std::move(fullimage)); } } - _result->filesize = (int32)qMin(filesize, qint64(INT_MAX)); + _result->filesize = (int32_t)qMin(filesize, int64_t(INT_MAX)); if (!filesize || filesize > App::kFileSizeLimit) { return; @@ -450,7 +450,7 @@ void FileLoadTask::process() { thumb = full; thumbSize = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); - thumbId = rand_value(); + thumbId = rand_value(); } } else if (auto video = base::get_if