From d6a35588244179781104673ca51e1197cabb4d53 Mon Sep 17 00:00:00 2001 From: Piotr Kosko Date: Wed, 4 Oct 2017 09:45:45 +0200 Subject: [PATCH 01/16] [Sensor] Fixed some bugs [Bug] - listener interval in case of multiple setListener calls was not updated - start/stop/setListener/unsetListener was not protected against multithread access - different behaviour in below scenarios: a.> HRMrawsensor = tizen.sensorservice.getDefaultSensor("HRM_RAW"); > HRMrawsensor.stop() undefined /// nothing happen b.> HRMrawsensor = tizen.sensorservice.getDefaultSensor("HRM_RAW"); > HRMrawsensor.start(function(s){console.log(s)}, function(s){console.log(s)}) WebAPIException {code: 9, name: "NotSupportedError", message: "None HRM LED sensor is supported."} > HRMrawsensor.stop() Uncaught WebAPIException {code: 9, name: "NotSupportedError", message: "None HRM LED sensor is supported."} [Verification] Manual and Auto TCT passed 100% (s.jastrzebsk) Change-Id: I4862823f84fc386d05eabfeb3dabb7345e9c592c Signed-off-by: Piotr Kosko Signed-off-by: Szymon Jastrzebski --- src/sensor/sensor_api.js | 10 +++- src/sensor/sensor_service.cc | 139 ++++++++++++++++++++++++++----------------- 2 files changed, 92 insertions(+), 57 deletions(-) diff --git a/src/sensor/sensor_api.js b/src/sensor/sensor_api.js index 8c34e33..2450cf2 100755 --- a/src/sensor/sensor_api.js +++ b/src/sensor/sensor_api.js @@ -61,6 +61,8 @@ var SensorListener = function (type, constructor) { this.sensorType = type; this.state = SensorStates.NOT_STARTED; this.callback = undefined; + this.callbackInterval = undefined; + this.callbackBatchLatency = undefined; this.constructor = constructor; }; @@ -78,6 +80,7 @@ SensorListener.prototype.start = function (successCallback, errorCallback) { native_.call('Sensor_start', {'sensorType' : thisObject.sensorType}, function(result) { if (native_.isFailure(result)) { + thisObject.state = SensorStates.NOT_STARTED; if (!T_.isNullOrUndefined(errorCallback)) { errorCallback(native_.getErrorObject(result)); } @@ -104,8 +107,9 @@ SensorListener.prototype.stop = function () { }; SensorListener.prototype.setListener = function (successCallback, interval, batchLatency) { - if (!this.callback) { - //call platform only if there was no listener registered + if (!this.callback || this.callbackInterval != interval || + this.callbackBatchLatency != batchLatency) { + //call platform only if there was no listener registered or parameters changed var result = native_.callSync('Sensor_setChangeListener', { 'sensorType' : this.sensorType, 'interval' : interval, @@ -115,6 +119,8 @@ SensorListener.prototype.setListener = function (successCallback, interval, batc throw native_.getErrorObject(result); } } + this.callbackInterval = interval; + this.callbackBatchLatency = batchLatency; this.callback = successCallback; }; diff --git a/src/sensor/sensor_service.cc b/src/sensor/sensor_service.cc index 95ebae2..2cd3ed6 100644 --- a/src/sensor/sensor_service.cc +++ b/src/sensor/sensor_service.cc @@ -234,7 +234,9 @@ class SensorData { common::optional is_supported_; SensorInstance& instance_; std::mutex initialization_mutex_; + std::mutex change_listener_mutex_; bool is_change_listener_set_; + bool is_starting_; std::vector> delayed_success_callbacks_; }; @@ -248,7 +250,8 @@ SensorData::SensorData(SensorInstance& instance, sensor_type_e type_enum, const previous_event_{0, 0, 0, -FLT_MAX}, // setting dumb non-zero value to differ init value from // "good" zero values from sensor instance_(instance), - is_change_listener_set_(false) { + is_change_listener_set_(false), + is_starting_(false) { type_to_string_map.insert(std::make_pair(type_enum, name)); string_to_type_map.insert(std::make_pair(name, type_enum)); @@ -275,19 +278,23 @@ void SensorData::SensorCallback(sensor_h sensor, sensor_event_s* event, void* us LoggerD("Entered: %s", type_to_string_map[that->type()].c_str()); - if (!that->delayed_success_callbacks_.empty()) { - for_each(that->delayed_success_callbacks_.begin(), that->delayed_success_callbacks_.end(), - [](std::function& callback) { - LoggerD("Calling delayed start succcess callback"); - callback(); - }); - that->delayed_success_callbacks_.erase(that->delayed_success_callbacks_.begin(), - that->delayed_success_callbacks_.end()); - if (!that->is_change_listener_set_) { - LoggerD("unregistering temporary listener used to delay start success callback"); - int ret = sensor_listener_unset_event_cb(that->listener_); - if (SENSOR_ERROR_NONE != ret) { - LoggerE("unsetting temporary listener failed: %d", ret); + { + std::lock_guard lock(that->change_listener_mutex_); + if (!that->delayed_success_callbacks_.empty()) { + for_each(that->delayed_success_callbacks_.begin(), that->delayed_success_callbacks_.end(), + [](std::function& callback) { + LoggerD("Calling delayed start succcess callback"); + callback(); + }); + that->delayed_success_callbacks_.erase(that->delayed_success_callbacks_.begin(), + that->delayed_success_callbacks_.end()); + if (!that->is_change_listener_set_) { + // if listener was not set from JS by developer, listener need to be unregistered + LoggerD("unregistering temporary listener used to delay start success callback"); + int ret = sensor_listener_unset_event_cb(that->listener_); + if (SENSOR_ERROR_NONE != ret) { + LoggerE("unsetting temporary listener failed: %d", ret); + } } } } @@ -388,9 +395,12 @@ bool SensorData::UpdateEvent(sensor_event_s* event) { PlatformResult SensorData::AddDelayedStartSuccessCb(const std::function& successCb) { LoggerD("Entered"); - delayed_success_callbacks_.push_back(successCb); - if (!is_change_listener_set_) { + delayed_success_callbacks_.push_back(successCb); + if (!is_change_listener_set_ && !is_starting_) { + // start method callback should be delayed to ensure that after triggering it, the actual + // data would be available on sensor, thus if listener is not registered yet, there is a need + // to register temporary change listener and call success callback on first change. LoggerD("Adding temporary listener by hand"); int ret = sensor_listener_set_event_cb(listener_, 10, // as small interval as possible for tmp listener @@ -421,18 +431,29 @@ PlatformResult SensorData::Start( ReportSuccess(result->get()); report_result(result); }; - res = AddDelayedStartSuccessCb(delayed_success_callback); - if (!res) { - return res; - } - sensor_listener_set_option(listener_, SENSOR_OPTION_ALWAYS_ON); - int ret = sensor_listener_start(listener_); - if (SENSOR_ERROR_NONE != ret) { - LoggerE("sensor_listener_start : %d", ret); - return GetSensorPlatformResult(ret, "sensor_listener_start"); - } + { + std::lock_guard lock(change_listener_mutex_); + res = AddDelayedStartSuccessCb(delayed_success_callback); + if (!res) { + return res; + } + if (!is_starting_) { + ScopeLogger("First attempt to start, starting listener on native level"); + sensor_listener_set_option(listener_, SENSOR_OPTION_ALWAYS_ON); + int ret = sensor_listener_start(listener_); + if (SENSOR_ERROR_NONE != ret) { + LoggerE("sensor_listener_start : %d", ret); + // removing delayed callback - listener starting failed + delayed_success_callbacks_.pop_back(); + return GetSensorPlatformResult(ret, "sensor_listener_start"); + } + is_starting_ = true; + } else { + LoggerD("Not calling native API, only delayed callback was added"); + } + } return PlatformResult(ErrorCode::NO_ERROR); } @@ -446,17 +467,21 @@ PlatformResult SensorData::Stop() { return res; } - int ret = sensor_listener_stop(listener_); - if (SENSOR_ERROR_NONE != ret) { - LoggerE("sensor_listener_stop : %d", ret); - return GetSensorPlatformResult(ret, "sensor_listener_stop"); - } + { + std::lock_guard lock(change_listener_mutex_); + int ret = sensor_listener_stop(listener_); + if (SENSOR_ERROR_NONE != ret) { + LoggerE("sensor_listener_stop : %d", ret); + return GetSensorPlatformResult(ret, "sensor_listener_stop"); + } - // reseting delayed success callbacks flag and saved event values - previous_event_ = {0, 0, 0, -FLT_MAX}; // setting dumb non-zero value to differ init value from - // "good" zero values from sensor - delayed_success_callbacks_.erase(delayed_success_callbacks_.begin(), - delayed_success_callbacks_.end()); + // reseting delayed success callbacks flag and saved event values + previous_event_ = {0, 0, 0, -FLT_MAX}; // setting dumb non-zero value to differ init value from + // "good" zero values from sensor + delayed_success_callbacks_.erase(delayed_success_callbacks_.begin(), + delayed_success_callbacks_.end()); + is_starting_ = false; + } return PlatformResult(ErrorCode::NO_ERROR); } @@ -470,24 +495,25 @@ PlatformResult SensorData::SetChangeListener(unsigned int interval, unsigned int LoggerE("Sensor initialization for sensor %s failed", type_to_string_map[type_enum_].c_str()); return res; } + { + std::lock_guard lock(change_listener_mutex_); + int ret = SENSOR_ERROR_NONE; + if (batch_latency > 0) { + ret = sensor_listener_set_max_batch_latency(listener_, batch_latency); + if (SENSOR_ERROR_NONE != ret) { + LoggerE("sensor_listener_set_max_batch_latency : %d", ret); + return GetSensorPlatformResult(ret, "Unable to set batchLatency"); + } + } - int ret = SENSOR_ERROR_NONE; - if (batch_latency > 0) { - ret = sensor_listener_set_max_batch_latency(listener_, batch_latency); + ret = sensor_listener_set_event_cb(listener_, interval, SensorCallback, this); if (SENSOR_ERROR_NONE != ret) { - LoggerE("sensor_listener_set_max_batch_latency : %d", ret); - return GetSensorPlatformResult(ret, "Unable to set batchLatency"); + LoggerE("sensor_listener_set_event_cb : %d", ret); + return GetSensorPlatformResult(ret, "sensor_listener_set_event_cb"); } + is_change_listener_set_ = true; } - ret = sensor_listener_set_event_cb(listener_, interval, SensorCallback, this); - if (SENSOR_ERROR_NONE != ret) { - LoggerE("sensor_listener_set_event_cb : %d", ret); - return GetSensorPlatformResult(ret, "sensor_listener_set_event_cb"); - } - - is_change_listener_set_ = true; - return PlatformResult(ErrorCode::NO_ERROR); } @@ -501,13 +527,16 @@ PlatformResult SensorData::UnsetChangeListener() { return res; } - int ret = sensor_listener_unset_event_cb(listener_); - if (SENSOR_ERROR_NONE != ret) { - LoggerE("sensor_listener_unset_event_cb : %d", ret); - return GetSensorPlatformResult(ret, "sensor_listener_unset_event_cb"); - } + { + std::lock_guard lock(change_listener_mutex_); + int ret = sensor_listener_unset_event_cb(listener_); + if (SENSOR_ERROR_NONE != ret) { + LoggerE("sensor_listener_unset_event_cb : %d", ret); + return GetSensorPlatformResult(ret, "sensor_listener_unset_event_cb"); + } - is_change_listener_set_ = false; + is_change_listener_set_ = false; + } return PlatformResult(ErrorCode::NO_ERROR); } -- 2.7.4 From f7a30738690f470858d3712f92ecaa3f4572f563 Mon Sep 17 00:00:00 2001 From: Piotr Kosko Date: Mon, 9 Oct 2017 13:57:35 +0200 Subject: [PATCH 02/16] [Tools] Added scripts for code style validation and auto fixing [Feature] Added below scripts: - tools/codestyle/code_formatter.sh - common formatter for both C and JS (changes files) - tools/codestyle/code_validation.sh - common validator for both C and JS (does not change files) - tools/codestyle/c++_clang_formatter.sh - for auto formating C++ files - tools/codestyle/js_clang_formatter.sh - for auto formating JS files - tools/codestyle/cpplint_tizen_160919.py and tools/codestyle/cpplint_tizen_dir.sh scripts for C++ code style validation, provided by HQ - tools/codestyle/eslint_config_mandatory_length90.js - coding rules for JS sources validation - provided by HQ - code_format and code_validate - links to scripts for easier access [Help] You can check usage for code_format and code_validate using '-h' option [Verification] Checked manually. Analysis seem to be done properly. Since now, we should reformat new code using: ./code_format -c and validate: ./code_validate -c Using scripts for JS sources is not recommended for now. Change-Id: I4af01a1f23c93547cd140ba7e5fed6294726c161 Signed-off-by: Piotr Kosko --- code_format | 1 + code_validate | 1 + tools/codestyle/README | 16 + tools/codestyle/c++_clang_formatter.sh | 54 + tools/codestyle/code_formatter.sh | 70 + tools/codestyle/code_validation.sh | 100 + tools/codestyle/cpplint_tizen_160919.py | 6343 ++++++++++++++++++++ tools/codestyle/cpplint_tizen_dir.sh | 14 + .../codestyle/eslint_config_mandatory_length90.js | 29 + tools/codestyle/js_clang_formatter.sh | 71 + 10 files changed, 6699 insertions(+) create mode 120000 code_format create mode 120000 code_validate create mode 100644 tools/codestyle/README create mode 100755 tools/codestyle/c++_clang_formatter.sh create mode 100755 tools/codestyle/code_formatter.sh create mode 100755 tools/codestyle/code_validation.sh create mode 100755 tools/codestyle/cpplint_tizen_160919.py create mode 100755 tools/codestyle/cpplint_tizen_dir.sh create mode 100644 tools/codestyle/eslint_config_mandatory_length90.js create mode 100755 tools/codestyle/js_clang_formatter.sh diff --git a/code_format b/code_format new file mode 120000 index 0000000..64aa937 --- /dev/null +++ b/code_format @@ -0,0 +1 @@ +tools/codestyle/code_formatter.sh \ No newline at end of file diff --git a/code_validate b/code_validate new file mode 120000 index 0000000..e4c7a49 --- /dev/null +++ b/code_validate @@ -0,0 +1 @@ +tools/codestyle/code_validation.sh \ No newline at end of file diff --git a/tools/codestyle/README b/tools/codestyle/README new file mode 100644 index 0000000..88746fb --- /dev/null +++ b/tools/codestyle/README @@ -0,0 +1,16 @@ + [Tools] Added scripts for code style validation and auto fixing + + [Features] + - tools/codestyle/code_formatter.sh - common formatter for both C/C++ and JS + (changes files) + - tools/codestyle/code_validation.sh - common validator for both C/C++ and JS + (does not change files) + - tools/codestyle/c++_clang_formatter.sh - for auto formating C++ files + - tools/codestyle/js_clang_formatter.sh - for auto formating JS files + - tools/codestyle/cpplint_tizen_160919.py and tools/codestyle/cpplint_tizen_dir.sh + scripts for C++ code style validation, provided by HQ + - tools/codestyle/eslint_config_mandatory_length90.js - coding rules for + JS sources validation - provided by HQ + - code_format and code_validate - links to scripts for easier access + + [Help] You can check usage for code_format and code_validate using '-h' option diff --git a/tools/codestyle/c++_clang_formatter.sh b/tools/codestyle/c++_clang_formatter.sh new file mode 100755 index 0000000..2d0f070 --- /dev/null +++ b/tools/codestyle/c++_clang_formatter.sh @@ -0,0 +1,54 @@ +#!/bin/bash + +#set -x +script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +# https://clangformat.com/ +command -v clang-format >/dev/null 2>&1 || { + echo >&2 "clang-format is required, but it's not installed"; + echo "-------------------------------------------------------------------------------------"; + echo "To install clang-format on Debian/Ubuntu, execute the following commands." + echo " sudo apt-get install clang-format-3.9" + echo " sudo ln -s /usr/bin/clang-format-3.9 /usr/bin/clang-format" + echo "-------------------------------------------------------------------------------------"; + exit 1; + } + +config='{ +BasedOnStyle: Google, +Language: Cpp, +Standard: Cpp11, +UseTab: Never, +IndentWidth: 2, +ColumnLimit: 100, +PointerBindsToType: true, +AllowShortFunctionsOnASingleLine: false, +}' + +formatC++() { + printf "." + # ignoring file not found errors + ls "$1"/*.cc &>/dev/null && clang-format -i -style="$config" "$1"/*.cc; + ls "$1"/*.cpp &>/dev/null && clang-format -i -style="$config" "$1"/*.cpp + ls "$1"/*.h &>/dev/null && clang-format -i -style="$config" "$1"/*.h + ls "$1"/*.hpp &>/dev/null && clang-format -i -style="$config" "$1"/*.hpp +} + +checkDirectoriesRecursively() { + dirs="$(find $1 -type d)" + for d in $dirs; + do + if [[ -d "$d" ]]; then + #echo "FORMAT $d" + formatC++ "$d"; + fi + done +} + +printf "C/C++ reformatting: "; +if [[ $# -eq 0 ]]; then + checkDirectoriesRecursively "src/" +else + checkDirectoriesRecursively "$1" +fi +printf "\nDONE C/C++ reformatting\n" diff --git a/tools/codestyle/code_formatter.sh b/tools/codestyle/code_formatter.sh new file mode 100755 index 0000000..2607d1a --- /dev/null +++ b/tools/codestyle/code_formatter.sh @@ -0,0 +1,70 @@ +#!/bin/bash +dir="$(dirname "$(readlink -f "$0")")" + +dir2analyze="$(pwd)/src" +analyzeJS="false"; +analyzeC="false"; + +printHelp() { + echo "Script for automatic fixing some coding style rules issues." + echo "In case of any issues of analysed code, the script would adjust it to follow" + echo "coding style. THIS COULD CHANGE YOUR FILES. Please commit your changes locally" + echo "if you want to have meaningful changes divided from style-only changes" + echo "Using it without specifying a path would analyse \"src\" from current directory." + printf -- "\nUsage: $(basename $0) [directory] [options ...]\n" + printf -- "Options:\n" + printf -- "-c\t\tcheck C/C++ files and fix issues\n" + printf -- "-js\t\tcheck JS files and fix issues\n" + printf -- "-a [--all]\tcheck all files JS and C/C++\n" + printf -- "-h [--help]\tshow this help\n" +} + +formatJsAndC++() { + path="$(readlink -f $1)" + if [[ "$analyzeC" == "true" ]]; then + echo "Reformatting C++ sources recursively for directory $path"; + $dir/c++_clang_formatter.sh "$path"; + else + echo "no C++ sources reformatting - please use '-c' option to enable it"; + fi + + if [[ "$analyzeJS" == "true" ]]; then + echo "Reformatting JS sources recursively for directory $path"; + $dir/js_clang_formatter.sh "$path"; + else + echo "no JS sources reformatting - please use '-js' option to enable it"; + fi +} + +for arg in "$@"; +do + if [[ "$arg" == "-u" ]]; then + echo "check updated files" + echo "TODO - Not supported yet" + exit + elif [[ "$arg" == "-c" ]]; then + analyzeC="true"; + elif [[ "$arg" == "-js" ]]; then + analyzeJS="true"; + elif [[ "$arg" == "--all" ]] || [[ "$arg" == "-a" ]]; then + analyzeJS="true"; + analyzeC="true"; + elif [[ "$arg" == "--help" ]] || [[ "$arg" == "-h" ]]; then + printHelp + exit + else + if [[ -d "$arg" ]]; then + dir2analyze="$arg"; + else + (>&2 printf "ERROR: directory '$arg' does not exist\n\n") + printHelp + exit 1 + fi + fi +done + +formatJsAndC++ "$dir2analyze" + +# some comments that probably could be useful while resolving TODO in future +# (git diff --name-only; git diff --name-only --cached) | grep "\.js" - modified JS files +# (git diff --name-only; git diff --name-only --cached) | grep "\.cc\|\.h\|\.cpp\|\.hpp" - modified C/C++ files diff --git a/tools/codestyle/code_validation.sh b/tools/codestyle/code_validation.sh new file mode 100755 index 0000000..ab89d67 --- /dev/null +++ b/tools/codestyle/code_validation.sh @@ -0,0 +1,100 @@ +#!/bin/bash +script_dir="$(dirname "$(readlink -f "$0")")" +config_file="eslint_config_mandatory_length90.js" + +dir2analyze="$(pwd)/src"; +analyzeJS="false"; +analyzeC="false"; + +printHelp() { + echo "Script for validation source code about coding style rules violations." + echo "The script would no change any files, only print report about found issues." + echo "Using it without specifying a path would analyse \"src\" from current directory." + printf -- "\nUsage: $(basename $0) [directory] [options ...]\n" + printf -- "Options:\n" + printf -- "-c\t\tcheck C/C++ files and fix issues\n" + printf -- "-js\t\tcheck JS files and fix issues\n" + printf -- "-a [--all]\tcheck all files JS and C/C++\n" + printf -- "-h [--help]\tshow this help\n" +} + +checkEslint() { + command -v eslint >/dev/null 2>&1 || { + echo >&2 "eslint is required, but it's not installed."; + echo "-------------------------------------------------------------------------------------"; + echo "If you want to make ESLint available to tools that run across all of your projects, we recommend installing ESLint globally. You can do so using npm" + echo "(it need to be installed on your machine - check https://www.rosehosting.com/blog/install-npm-on-ubuntu-16-04/):" + echo "$ sudo npm install -g eslint" + echo "-------------------------------------------------------------------------------------"; + exit 1; + } +} + +checkC() { + printf "." + echo "Checking C style of $1 directory" + $script_dir/cpplint_tizen_dir.sh "$1" +} + +checkJS() { + ls "$1"/*.js &>/dev/null + if [[ "$?" -eq 0 ]]; then + printf "." + echo "Checking JS style of $1 directory" + eslint -c "$script_dir/$config_file" "$1"/*.js + fi +} + +checkJsAndC++() { + path=$(readlink -f $1) + if [[ "$analyzeC" = true ]]; then + echo "Checking C++ recursively for directory $path" + checkC "$path" + else + echo "no C++ sources validation"; + fi + + if [[ "$analyzeJS" = "true" ]]; then + echo "Checking JS recursively for directory $path" + checkEslint + dirs=$(find $path -type d) + for d in $dirs; + do + if [[ -d "$d" ]]; then + checkJS "$d"; + fi + done + else + echo "no JS sources validation"; + fi +} + + +for arg in "$@"; +do + if [[ "$arg" == "-u" ]]; then + echo "check updated files" + echo "TODO - Not supported yet" + exit + elif [[ "$arg" == "-c" ]]; then + analyzeC="true"; + elif [[ "$arg" == "-js" ]]; then + analyzeJS="true"; + elif [[ "$arg" == "--all" ]] || [[ "$arg" == "-a" ]]; then + analyzeJS="true"; + analyzeC="true"; + elif [[ "$arg" == "--help" ]] || [[ "$arg" == "-h" ]]; then + printHelp + exit + else + if [[ -d "$arg" ]]; then + dir2analyze="$arg"; + else + (>&2 printf "ERROR: directory '$arg' does not exist\n\n") + printHelp + exit 1 + fi + fi +done + +checkJsAndC++ "$dir2analyze" diff --git a/tools/codestyle/cpplint_tizen_160919.py b/tools/codestyle/cpplint_tizen_160919.py new file mode 100755 index 0000000..b327ce2 --- /dev/null +++ b/tools/codestyle/cpplint_tizen_160919.py @@ -0,0 +1,6343 @@ +#!/usr/bin/env python +# +# Copyright (c) 2009 Google Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#for tizen 20160919 + +"""Does google-lint on c++ files. + +The goal of this script is to identify places in the code that *may* +be in non-compliance with google style. It does not attempt to fix +up these problems -- the point is to educate. It does also not +attempt to find all problems, or to ensure that everything it does +find is legitimately a problem. + +In particular, we can get very confused by /* and // inside strings! +We do a small hack, which is to ignore //'s with "'s after them on the +same line, but it is far from perfect (in either direction). +""" + +import codecs +import copy +import getopt +import math # for log +import os +import re +import sre_compile +import string +import sys +import unicodedata + + +_USAGE = """ +Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...] + [--counting=total|toplevel|detailed] [--root=subdir] + [--linelength=digits] + [file] ... + + The style guidelines this tries to follow are those in + http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml + + Every problem is given a confidence score from 1-5, with 5 meaning we are + certain of the problem, and 1 meaning it could be a legitimate construct. + This will miss some errors, and is not a substitute for a code review. + + To suppress false-positive errors of a certain category, add a + 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) + suppresses errors of all categories on that line. + + The files passed in will be linted; at least one file must be provided. + Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the + extensions with the --extensions flag. + + Flags: + + output=vs7 + By default, the output is formatted to ease emacs parsing. Visual Studio + compatible output (vs7) may also be used. Other formats are unsupported. + + verbose=# + Specify a number 0-5 to restrict errors to certain verbosity levels. + + filter=-x,+y,... + Specify a comma-separated list of category-filters to apply: only + error messages whose category names pass the filters will be printed. + (Category names are printed with the message and look like + "[whitespace/indent]".) Filters are evaluated left to right. + "-FOO" and "FOO" means "do not print categories that start with FOO". + "+FOO" means "do print categories that start with FOO". + + Examples: --filter=-whitespace,+whitespace/braces + --filter=whitespace,runtime/printf,+runtime/printf_format + --filter=-,+build/include_what_you_use + + To see a list of all the categories used in cpplint, pass no arg: + --filter= + + counting=total|toplevel|detailed + The total number of errors found is always printed. If + 'toplevel' is provided, then the count of errors in each of + the top-level categories like 'build' and 'whitespace' will + also be printed. If 'detailed' is provided, then a count + is provided for each category like 'build/class'. + + root=subdir + The root directory used for deriving header guard CPP variable. + By default, the header guard CPP variable is calculated as the relative + path to the directory that contains .git, .hg, or .svn. When this flag + is specified, the relative path is calculated from the specified + directory. If the specified directory does not exist, this flag is + ignored. + + Examples: + Assuming that src/.git exists, the header guard CPP variables for + src/chrome/browser/ui/browser.h are: + + No flag => CHROME_BROWSER_UI_BROWSER_H_ + --root=chrome => BROWSER_UI_BROWSER_H_ + --root=chrome/browser => UI_BROWSER_H_ + + linelength=digits + This is the allowed line length for the project. The default value is + 80 characters. + + Examples: + --linelength=120 + + extensions=extension,extension,... + The allowed file extensions that cpplint will check + + Examples: + --extensions=hpp,cpp + + cpplint.py supports per-directory configurations specified in CPPLINT.cfg + files. CPPLINT.cfg file can contain a number of key=value pairs. + Currently the following options are supported: + + set noparent + filter=+filter1,-filter2,... + exclude_files=regex + linelength=80 + + "set noparent" option prevents cpplint from traversing directory tree + upwards looking for more .cfg files in parent directories. This option + is usually placed in the top-level project directory. + + The "filter" option is similar in function to --filter flag. It specifies + message filters in addition to the |_DEFAULT_FILTERS| and those specified + through --filter command-line flag. + + "exclude_files" allows to specify a regular expression to be matched against + a file name. If the expression matches, the file is skipped and not run + through liner. + + "linelength" allows to specify the allowed line length for the project. + + CPPLINT.cfg has an effect on files in the same directory and all + sub-directories, unless overridden by a nested configuration file. + + Example file: + filter=-build/include_order,+build/include_alpha + exclude_files=.*\.cc + + The above example disables build/include_order warning and enables + build/include_alpha as well as excludes all .cc from being + processed by linter, in the current directory (where the .cfg + file is located) and all sub-directories. +""" + +# We categorize each error message we print. Here are the categories. +# We want an explicit list so we can list them all in cpplint --filter=. +# If you add a new error message with a new category, add it to the list +# here! cpplint_unittest.py should tell you if you forget to do this. +_ERROR_CATEGORIES = [ + 'build/class', + 'build/c++11', + 'build/deprecated', + 'build/endif_comment', + 'build/explicit_make_pair', + 'build/forward_decl', + 'build/header_guard', + 'build/include', + 'build/include_alpha', + 'build/include_order', + 'build/include_what_you_use', + 'build/namespaces', + 'build/printf_format', + 'build/storage_class', + 'legal/copyright', + 'readability/alt_tokens', + 'readability/braces', + 'readability/casting', + 'readability/check', + 'readability/constructors', + 'readability/fn_size', + 'readability/function', + 'readability/inheritance', + 'readability/multiline_comment', + 'readability/multiline_string', + 'readability/namespace', + 'readability/nolint', + 'readability/nul', + 'readability/strings', + 'readability/todo', + 'readability/utf8', + 'runtime/arrays', + 'runtime/casting', + 'runtime/explicit', + 'runtime/int', + 'runtime/init', + 'runtime/invalid_increment', + 'runtime/member_string_references', + 'runtime/memset', + 'runtime/indentation_namespace', + 'runtime/operator', + 'runtime/printf', + 'runtime/printf_format', + 'runtime/references', + 'runtime/string', + 'runtime/threadsafe_fn', + 'runtime/vlog', + 'whitespace/blank_line', + 'whitespace/braces', + 'whitespace/comma', + 'whitespace/comments', + 'whitespace/empty_conditional_body', + 'whitespace/empty_loop_body', + 'whitespace/end_of_line', + 'whitespace/ending_newline', + 'whitespace/forcolon', + 'whitespace/indent', + 'whitespace/line_length', + 'whitespace/newline', + 'whitespace/operators', + 'whitespace/parens', + 'whitespace/semicolon', + 'whitespace/tab', + 'whitespace/todo', + ] + +# These error categories are no longer enforced by cpplint, but for backwards- +# compatibility they may still appear in NOLINT comments. +_LEGACY_ERROR_CATEGORIES = [ + 'readability/streams', + ] + +# The default state of the category filter. This is overridden by the --filter= +# flag. By default all errors are on, so only add here categories that should be +# off by default (i.e., categories that must be enabled by the --filter= flags). +# All entries here should start with a '-' or '+', as in the --filter= flag. +_DEFAULT_FILTERS = ['-build/include_alpha'] + +# We used to check for high-bit characters, but after much discussion we +# decided those were OK, as long as they were in UTF-8 and didn't represent +# hard-coded international strings, which belong in a separate i18n file. + +# C++ headers +_CPP_HEADERS = frozenset([ + # Legacy + 'algobase.h', + 'algo.h', + 'alloc.h', + 'builtinbuf.h', + 'bvector.h', + 'complex.h', + 'defalloc.h', + 'deque.h', + 'editbuf.h', + 'fstream.h', + 'function.h', + 'hash_map', + 'hash_map.h', + 'hash_set', + 'hash_set.h', + 'hashtable.h', + 'heap.h', + 'indstream.h', + 'iomanip.h', + 'iostream.h', + 'istream.h', + 'iterator.h', + 'list.h', + 'map.h', + 'multimap.h', + 'multiset.h', + 'ostream.h', + 'pair.h', + 'parsestream.h', + 'pfstream.h', + 'procbuf.h', + 'pthread_alloc', + 'pthread_alloc.h', + 'rope', + 'rope.h', + 'ropeimpl.h', + 'set.h', + 'slist', + 'slist.h', + 'stack.h', + 'stdiostream.h', + 'stl_alloc.h', + 'stl_relops.h', + 'streambuf.h', + 'stream.h', + 'strfile.h', + 'strstream.h', + 'tempbuf.h', + 'tree.h', + 'type_traits.h', + 'vector.h', + # 17.6.1.2 C++ library headers + 'algorithm', + 'array', + 'atomic', + 'bitset', + 'chrono', + 'codecvt', + 'complex', + 'condition_variable', + 'deque', + 'exception', + 'forward_list', + 'fstream', + 'functional', + 'future', + 'initializer_list', + 'iomanip', + 'ios', + 'iosfwd', + 'iostream', + 'istream', + 'iterator', + 'limits', + 'list', + 'locale', + 'map', + 'memory', + 'mutex', + 'new', + 'numeric', + 'ostream', + 'queue', + 'random', + 'ratio', + 'regex', + 'set', + 'sstream', + 'stack', + 'stdexcept', + 'streambuf', + 'string', + 'strstream', + 'system_error', + 'thread', + 'tuple', + 'typeindex', + 'typeinfo', + 'type_traits', + 'unordered_map', + 'unordered_set', + 'utility', + 'valarray', + 'vector', + # 17.6.1.2 C++ headers for C library facilities + 'cassert', + 'ccomplex', + 'cctype', + 'cerrno', + 'cfenv', + 'cfloat', + 'cinttypes', + 'ciso646', + 'climits', + 'clocale', + 'cmath', + 'csetjmp', + 'csignal', + 'cstdalign', + 'cstdarg', + 'cstdbool', + 'cstddef', + 'cstdint', + 'cstdio', + 'cstdlib', + 'cstring', + 'ctgmath', + 'ctime', + 'cuchar', + 'cwchar', + 'cwctype', + ]) + + +# These headers are excluded from [build/include] and [build/include_order] +# checks: +# - Anything not following google file name conventions (containing an +# uppercase character, such as Python.h or nsStringAPI.h, for example). +# - Lua headers. +_THIRD_PARTY_HEADERS_PATTERN = re.compile( + r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$') + + +# Assertion macros. These are defined in base/logging.h and +# testing/base/gunit.h. Note that the _M versions need to come first +# for substring matching to work. +_CHECK_MACROS = [ + 'DCHECK', 'CHECK', + 'EXPECT_TRUE_M', 'EXPECT_TRUE', + 'ASSERT_TRUE_M', 'ASSERT_TRUE', + 'EXPECT_FALSE_M', 'EXPECT_FALSE', + 'ASSERT_FALSE_M', 'ASSERT_FALSE', + ] + +# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE +_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS]) + +for op, replacement in [('==', 'EQ'), ('!=', 'NE'), + ('>=', 'GE'), ('>', 'GT'), + ('<=', 'LE'), ('<', 'LT')]: + _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement + _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement + _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement + _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement + _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement + _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement + +for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), + ('>=', 'LT'), ('>', 'LE'), + ('<=', 'GT'), ('<', 'GE')]: + _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement + _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement + _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement + _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement + +# Alternative tokens and their replacements. For full list, see section 2.5 +# Alternative tokens [lex.digraph] in the C++ standard. +# +# Digraphs (such as '%:') are not included here since it's a mess to +# match those on a word boundary. +_ALT_TOKEN_REPLACEMENT = { + 'and': '&&', + 'bitor': '|', + 'or': '||', + 'xor': '^', + 'compl': '~', + 'bitand': '&', + 'and_eq': '&=', + 'or_eq': '|=', + 'xor_eq': '^=', + 'not': '!', + 'not_eq': '!=' + } + +# Compile regular expression that matches all the above keywords. The "[ =()]" +# bit is meant to avoid matching these keywords outside of boolean expressions. +# +# False positives include C-style multi-line comments and multi-line strings +# but those have always been troublesome for cpplint. +_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( + r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') + + +# These constants define types of headers for use with +# _IncludeState.CheckNextIncludeOrder(). +_C_SYS_HEADER = 1 +_CPP_SYS_HEADER = 2 +_LIKELY_MY_HEADER = 3 +_POSSIBLE_MY_HEADER = 4 +_OTHER_HEADER = 5 + +# These constants define the current inline assembly state +_NO_ASM = 0 # Outside of inline assembly block +_INSIDE_ASM = 1 # Inside inline assembly block +_END_ASM = 2 # Last line of inline assembly block +_BLOCK_ASM = 3 # The whole block is an inline assembly block + +# Match start of assembly blocks +_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)' + r'(?:\s+(volatile|__volatile__))?' + r'\s*[{(]') + + +_regexp_compile_cache = {} + +# {str, set(int)}: a map from error categories to sets of linenumbers +# on which those errors are expected and should be suppressed. +_error_suppressions = {} + +# The root directory used for deriving header guard CPP variable. +# This is set by --root flag. +_root = None + +# The allowed line length of files. +# This is set by --linelength flag. +_line_length = 80 + +# The allowed extensions for file names +# This is set by --extensions flag. +_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh']) + +def ParseNolintSuppressions(filename, raw_line, linenum, error): + """Updates the global list of error-suppressions. + + Parses any NOLINT comments on the current line, updating the global + error_suppressions store. Reports an error if the NOLINT comment + was malformed. + + Args: + filename: str, the name of the input file. + raw_line: str, the line of input text, with comments. + linenum: int, the number of the current line. + error: function, an error handler. + """ + matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line) + if matched: + if matched.group(1): + suppressed_line = linenum + 1 + else: + suppressed_line = linenum + category = matched.group(2) + if category in (None, '(*)'): # => "suppress all" + _error_suppressions.setdefault(None, set()).add(suppressed_line) + else: + if category.startswith('(') and category.endswith(')'): + category = category[1:-1] + if category in _ERROR_CATEGORIES: + _error_suppressions.setdefault(category, set()).add(suppressed_line) + elif category not in _LEGACY_ERROR_CATEGORIES: + error(filename, linenum, 'readability/nolint', 5, + 'Unknown NOLINT error category: %s' % category) + + +def ResetNolintSuppressions(): + """Resets the set of NOLINT suppressions to empty.""" + _error_suppressions.clear() + + +def IsErrorSuppressedByNolint(category, linenum): + """Returns true if the specified error category is suppressed on this line. + + Consults the global error_suppressions map populated by + ParseNolintSuppressions/ResetNolintSuppressions. + + Args: + category: str, the category of the error. + linenum: int, the current line number. + Returns: + bool, True iff the error should be suppressed due to a NOLINT comment. + """ + return (linenum in _error_suppressions.get(category, set()) or + linenum in _error_suppressions.get(None, set())) + + +def Match(pattern, s): + """Matches the string with the pattern, caching the compiled regexp.""" + # The regexp compilation caching is inlined in both Match and Search for + # performance reasons; factoring it out into a separate function turns out + # to be noticeably expensive. + if pattern not in _regexp_compile_cache: + _regexp_compile_cache[pattern] = sre_compile.compile(pattern) + return _regexp_compile_cache[pattern].match(s) + + +def ReplaceAll(pattern, rep, s): + """Replaces instances of pattern in a string with a replacement. + + The compiled regex is kept in a cache shared by Match and Search. + + Args: + pattern: regex pattern + rep: replacement text + s: search string + + Returns: + string with replacements made (or original string if no replacements) + """ + if pattern not in _regexp_compile_cache: + _regexp_compile_cache[pattern] = sre_compile.compile(pattern) + return _regexp_compile_cache[pattern].sub(rep, s) + + +def Search(pattern, s): + """Searches the string for the pattern, caching the compiled regexp.""" + if pattern not in _regexp_compile_cache: + _regexp_compile_cache[pattern] = sre_compile.compile(pattern) + return _regexp_compile_cache[pattern].search(s) + + +class _IncludeState(object): + """Tracks line numbers for includes, and the order in which includes appear. + + include_list contains list of lists of (header, line number) pairs. + It's a lists of lists rather than just one flat list to make it + easier to update across preprocessor boundaries. + + Call CheckNextIncludeOrder() once for each header in the file, passing + in the type constants defined above. Calls in an illegal order will + raise an _IncludeError with an appropriate error message. + + """ + # self._section will move monotonically through this set. If it ever + # needs to move backwards, CheckNextIncludeOrder will raise an error. + _INITIAL_SECTION = 0 + _MY_H_SECTION = 1 + _C_SECTION = 2 + _CPP_SECTION = 3 + _OTHER_H_SECTION = 4 + + _TYPE_NAMES = { + _C_SYS_HEADER: 'C system header', + _CPP_SYS_HEADER: 'C++ system header', + _LIKELY_MY_HEADER: 'header this file implements', + _POSSIBLE_MY_HEADER: 'header this file may implement', + _OTHER_HEADER: 'other header', + } + _SECTION_NAMES = { + _INITIAL_SECTION: "... nothing. (This can't be an error.)", + _MY_H_SECTION: 'a header this file implements', + _C_SECTION: 'C system header', + _CPP_SECTION: 'C++ system header', + _OTHER_H_SECTION: 'other header', + } + + def __init__(self): + self.include_list = [[]] + self.ResetSection('') + + def FindHeader(self, header): + """Check if a header has already been included. + + Args: + header: header to check. + Returns: + Line number of previous occurrence, or -1 if the header has not + been seen before. + """ + for section_list in self.include_list: + for f in section_list: + if f[0] == header: + return f[1] + return -1 + + def ResetSection(self, directive): + """Reset section checking for preprocessor directive. + + Args: + directive: preprocessor directive (e.g. "if", "else"). + """ + # The name of the current section. + self._section = self._INITIAL_SECTION + # The path of last found header. + self._last_header = '' + + # Update list of includes. Note that we never pop from the + # include list. + if directive in ('if', 'ifdef', 'ifndef'): + self.include_list.append([]) + elif directive in ('else', 'elif'): + self.include_list[-1] = [] + + def SetLastHeader(self, header_path): + self._last_header = header_path + + def CanonicalizeAlphabeticalOrder(self, header_path): + """Returns a path canonicalized for alphabetical comparison. + + - replaces "-" with "_" so they both cmp the same. + - removes '-inl' since we don't require them to be after the main header. + - lowercase everything, just in case. + + Args: + header_path: Path to be canonicalized. + + Returns: + Canonicalized path. + """ + return header_path.replace('-inl.h', '.h').replace('-', '_').lower() + + def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): + """Check if a header is in alphabetical order with the previous header. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + header_path: Canonicalized header to be checked. + + Returns: + Returns true if the header is in alphabetical order. + """ + # If previous section is different from current section, _last_header will + # be reset to empty string, so it's always less than current header. + # + # If previous line was a blank line, assume that the headers are + # intentionally sorted the way they are. + if (self._last_header > header_path and + Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])): + return False + return True + + def CheckNextIncludeOrder(self, header_type): + """Returns a non-empty error message if the next header is out of order. + + This function also updates the internal state to be ready to check + the next include. + + Args: + header_type: One of the _XXX_HEADER constants defined above. + + Returns: + The empty string if the header is in the right order, or an + error message describing what's wrong. + + """ + error_message = ('Found %s after %s' % + (self._TYPE_NAMES[header_type], + self._SECTION_NAMES[self._section])) + + last_section = self._section + + if header_type == _C_SYS_HEADER: + if self._section <= self._C_SECTION: + self._section = self._C_SECTION + else: + self._last_header = '' + return error_message + elif header_type == _CPP_SYS_HEADER: + if self._section <= self._CPP_SECTION: + self._section = self._CPP_SECTION + else: + self._last_header = '' + return error_message + elif header_type == _LIKELY_MY_HEADER: + if self._section <= self._MY_H_SECTION: + self._section = self._MY_H_SECTION + else: + self._section = self._OTHER_H_SECTION + elif header_type == _POSSIBLE_MY_HEADER: + if self._section <= self._MY_H_SECTION: + self._section = self._MY_H_SECTION + else: + # This will always be the fallback because we're not sure + # enough that the header is associated with this file. + self._section = self._OTHER_H_SECTION + else: + assert header_type == _OTHER_HEADER + self._section = self._OTHER_H_SECTION + + if last_section != self._section: + self._last_header = '' + + return '' + + +class _CppLintState(object): + """Maintains module-wide state..""" + + def __init__(self): + self.verbose_level = 1 # global setting. + self.error_count = 0 # global count of reported errors + # filters to apply when emitting error messages + self.filters = _DEFAULT_FILTERS[:] + # backup of filter list. Used to restore the state after each file. + self._filters_backup = self.filters[:] + self.counting = 'total' # In what way are we counting errors? + self.errors_by_category = {} # string to int dict storing error counts + + # output format: + # "emacs" - format that emacs can parse (default) + # "vs7" - format that Microsoft Visual Studio 7 can parse + self.output_format = 'emacs' + + def SetOutputFormat(self, output_format): + """Sets the output format for errors.""" + self.output_format = output_format + + def SetVerboseLevel(self, level): + """Sets the module's verbosity, and returns the previous setting.""" + last_verbose_level = self.verbose_level + self.verbose_level = level + return last_verbose_level + + def SetCountingStyle(self, counting_style): + """Sets the module's counting options.""" + self.counting = counting_style + + def SetFilters(self, filters): + """Sets the error-message filters. + + These filters are applied when deciding whether to emit a given + error message. + + Args: + filters: A string of comma-separated filters (eg "+whitespace/indent"). + Each filter should start with + or -; else we die. + + Raises: + ValueError: The comma-separated filters did not all start with '+' or '-'. + E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" + """ + # Default filters always have less priority than the flag ones. + self.filters = _DEFAULT_FILTERS[:] + self.AddFilters(filters) + + def AddFilters(self, filters): + """ Adds more filters to the existing list of error-message filters. """ + for filt in filters.split(','): + clean_filt = filt.strip() + if clean_filt: + self.filters.append(clean_filt) + for filt in self.filters: + if not (filt.startswith('+') or filt.startswith('-')): + raise ValueError('Every filter in --filters must start with + or -' + ' (%s does not)' % filt) + + def BackupFilters(self): + """ Saves the current filter list to backup storage.""" + self._filters_backup = self.filters[:] + + def RestoreFilters(self): + """ Restores filters previously backed up.""" + self.filters = self._filters_backup[:] + + def ResetErrorCounts(self): + """Sets the module's error statistic back to zero.""" + self.error_count = 0 + self.errors_by_category = {} + + def IncrementErrorCount(self, category): + """Bumps the module's error statistic.""" + self.error_count += 1 + if self.counting in ('toplevel', 'detailed'): + if self.counting != 'detailed': + category = category.split('/')[0] + if category not in self.errors_by_category: + self.errors_by_category[category] = 0 + self.errors_by_category[category] += 1 + + def PrintErrorCounts(self): + """Print a summary of errors by category, and the total.""" + for category, count in self.errors_by_category.iteritems(): + sys.stderr.write('Category \'%s\' errors found: %d\n' % + (category, count)) + sys.stderr.write('Total errors found: %d\n' % self.error_count) + +_cpplint_state = _CppLintState() + + +def _OutputFormat(): + """Gets the module's output format.""" + return _cpplint_state.output_format + + +def _SetOutputFormat(output_format): + """Sets the module's output format.""" + _cpplint_state.SetOutputFormat(output_format) + + +def _VerboseLevel(): + """Returns the module's verbosity setting.""" + return _cpplint_state.verbose_level + + +def _SetVerboseLevel(level): + """Sets the module's verbosity, and returns the previous setting.""" + return _cpplint_state.SetVerboseLevel(level) + + +def _SetCountingStyle(level): + """Sets the module's counting options.""" + _cpplint_state.SetCountingStyle(level) + + +def _Filters(): + """Returns the module's list of output filters, as a list.""" + return _cpplint_state.filters + + +def _SetFilters(filters): + """Sets the module's error-message filters. + + These filters are applied when deciding whether to emit a given + error message. + + Args: + filters: A string of comma-separated filters (eg "whitespace/indent"). + Each filter should start with + or -; else we die. + """ + _cpplint_state.SetFilters(filters) + +def _AddFilters(filters): + """Adds more filter overrides. + + Unlike _SetFilters, this function does not reset the current list of filters + available. + + Args: + filters: A string of comma-separated filters (eg "whitespace/indent"). + Each filter should start with + or -; else we die. + """ + _cpplint_state.AddFilters(filters) + +def _BackupFilters(): + """ Saves the current filter list to backup storage.""" + _cpplint_state.BackupFilters() + +def _RestoreFilters(): + """ Restores filters previously backed up.""" + _cpplint_state.RestoreFilters() + +class _FunctionState(object): + """Tracks current function name and the number of lines in its body.""" + + _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. + _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. + + def __init__(self): + self.in_a_function = False + self.lines_in_function = 0 + self.current_function = '' + + def Begin(self, function_name): + """Start analyzing function body. + + Args: + function_name: The name of the function being tracked. + """ + self.in_a_function = True + self.lines_in_function = 0 + self.current_function = function_name + + def Count(self): + """Count line in current function body.""" + if self.in_a_function: + self.lines_in_function += 1 + + def Check(self, error, filename, linenum): + """Report if too many lines in function body. + + Args: + error: The function to call with any errors found. + filename: The name of the current file. + linenum: The number of the line to check. + """ + if Match(r'T(EST|est)', self.current_function): + base_trigger = self._TEST_TRIGGER + else: + base_trigger = self._NORMAL_TRIGGER + trigger = base_trigger * 2**_VerboseLevel() + + if self.lines_in_function > trigger: + error_level = int(math.log(self.lines_in_function / base_trigger, 2)) + # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... + if error_level > 5: + error_level = 5 + error(filename, linenum, 'readability/fn_size', error_level, + 'Small and focused functions are preferred:' + ' %s has %d non-comment lines' + ' (error triggered by exceeding %d lines).' % ( + self.current_function, self.lines_in_function, trigger)) + + def End(self): + """Stop analyzing function body.""" + self.in_a_function = False + + +class _IncludeError(Exception): + """Indicates a problem with the include order in a file.""" + pass + + +class FileInfo(object): + """Provides utility functions for filenames. + + FileInfo provides easy access to the components of a file's path + relative to the project root. + """ + + def __init__(self, filename): + self._filename = filename + + def FullName(self): + """Make Windows paths like Unix.""" + return os.path.abspath(self._filename).replace('\\', '/') + + def RepositoryName(self): + """FullName after removing the local path to the repository. + + If we have a real absolute path name here we can try to do something smart: + detecting the root of the checkout and truncating /path/to/checkout from + the name so that we get header guards that don't include things like + "C:\Documents and Settings\..." or "/home/username/..." in them and thus + people on different computers who have checked the source out to different + locations won't see bogus errors. + """ + fullname = self.FullName() + + if os.path.exists(fullname): + project_dir = os.path.dirname(fullname) + + if os.path.exists(os.path.join(project_dir, ".svn")): + # If there's a .svn file in the current directory, we recursively look + # up the directory tree for the top of the SVN checkout + root_dir = project_dir + one_up_dir = os.path.dirname(root_dir) + while os.path.exists(os.path.join(one_up_dir, ".svn")): + root_dir = os.path.dirname(root_dir) + one_up_dir = os.path.dirname(one_up_dir) + + prefix = os.path.commonprefix([root_dir, project_dir]) + return fullname[len(prefix) + 1:] + + # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by + # searching up from the current path. + root_dir = os.path.dirname(fullname) + while (root_dir != os.path.dirname(root_dir) and + not os.path.exists(os.path.join(root_dir, ".git")) and + not os.path.exists(os.path.join(root_dir, ".hg")) and + not os.path.exists(os.path.join(root_dir, ".svn"))): + root_dir = os.path.dirname(root_dir) + + if (os.path.exists(os.path.join(root_dir, ".git")) or + os.path.exists(os.path.join(root_dir, ".hg")) or + os.path.exists(os.path.join(root_dir, ".svn"))): + prefix = os.path.commonprefix([root_dir, project_dir]) + return fullname[len(prefix) + 1:] + + # Don't know what to do; header guard warnings may be wrong... + return fullname + + def Split(self): + """Splits the file into the directory, basename, and extension. + + For 'chrome/browser/browser.cc', Split() would + return ('chrome/browser', 'browser', '.cc') + + Returns: + A tuple of (directory, basename, extension). + """ + + googlename = self.RepositoryName() + project, rest = os.path.split(googlename) + return (project,) + os.path.splitext(rest) + + def BaseName(self): + """File base name - text after the final slash, before the final period.""" + return self.Split()[1] + + def Extension(self): + """File extension - text following the final period.""" + return self.Split()[2] + + def NoExtension(self): + """File has no source file extension.""" + return '/'.join(self.Split()[0:2]) + + def IsSource(self): + """File has a source file extension.""" + return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') + + +def _ShouldPrintError(category, confidence, linenum): + """If confidence >= verbose, category passes filter and is not suppressed.""" + + # There are three ways we might decide not to print an error message: + # a "NOLINT(category)" comment appears in the source, + # the verbosity level isn't high enough, or the filters filter it out. + if IsErrorSuppressedByNolint(category, linenum): + return False + + if confidence < _cpplint_state.verbose_level: + return False + + is_filtered = False + for one_filter in _Filters(): + if one_filter.startswith('-'): + if category.startswith(one_filter[1:]): + is_filtered = True + elif one_filter.startswith('+'): + if category.startswith(one_filter[1:]): + is_filtered = False + else: + assert False # should have been checked for in SetFilter. + if is_filtered: + return False + + return True + + +def Error(filename, linenum, category, confidence, message): + """Logs the fact we've found a lint error. + + We log where the error was found, and also our confidence in the error, + that is, how certain we are this is a legitimate style regression, and + not a misidentification or a use that's sometimes justified. + + False positives can be suppressed by the use of + "cpplint(category)" comments on the offending line. These are + parsed into _error_suppressions. + + Args: + filename: The name of the file containing the error. + linenum: The number of the line containing the error. + category: A string used to describe the "category" this bug + falls under: "whitespace", say, or "runtime". Categories + may have a hierarchy separated by slashes: "whitespace/indent". + confidence: A number from 1-5 representing a confidence score for + the error, with 5 meaning that we are certain of the problem, + and 1 meaning that it could be a legitimate construct. + message: The error message. + """ + if _ShouldPrintError(category, confidence, linenum): + _cpplint_state.IncrementErrorCount(category) + if _cpplint_state.output_format == 'vs7': + sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( + filename, linenum, message, category, confidence)) + elif _cpplint_state.output_format == 'eclipse': + sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( + filename, linenum, message, category, confidence)) + else: + sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( + filename, linenum, message, category, confidence)) + + +# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard. +_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( + r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') +# Match a single C style comment on the same line. +_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/' +# Matches multi-line C style comments. +# This RE is a little bit more complicated than one might expect, because we +# have to take care of space removals tools so we can handle comments inside +# statements better. +# The current rule is: We only clear spaces from both sides when we're at the +# end of the line. Otherwise, we try to remove spaces from the right side, +# if this doesn't work we try on left side but only if there's a non-character +# on the right. +_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( + r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' + + _RE_PATTERN_C_COMMENTS + r'\s+|' + + r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' + + _RE_PATTERN_C_COMMENTS + r')') + + +def IsCppString(line): + """Does line terminate so, that the next symbol is in string constant. + + This function does not consider single-line nor multi-line comments. + + Args: + line: is a partial line of code starting from the 0..n. + + Returns: + True, if next character appended to 'line' is inside a + string constant. + """ + + line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" + return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 + + +def CleanseRawStrings(raw_lines): + """Removes C++11 raw strings from lines. + + Before: + static const char kData[] = R"( + multi-line string + )"; + + After: + static const char kData[] = "" + (replaced by blank line) + ""; + + Args: + raw_lines: list of raw lines. + + Returns: + list of lines with C++11 raw strings replaced by empty strings. + """ + + delimiter = None + lines_without_raw_strings = [] + for line in raw_lines: + if delimiter: + # Inside a raw string, look for the end + end = line.find(delimiter) + if end >= 0: + # Found the end of the string, match leading space for this + # line and resume copying the original lines, and also insert + # a "" on the last line. + leading_space = Match(r'^(\s*)\S', line) + line = leading_space.group(1) + '""' + line[end + len(delimiter):] + delimiter = None + else: + # Haven't found the end yet, append a blank line. + line = '""' + + # Look for beginning of a raw string, and replace them with + # empty strings. This is done in a loop to handle multiple raw + # strings on the same line. + while delimiter is None: + # Look for beginning of a raw string. + # See 2.14.15 [lex.string] for syntax. + matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) + if matched: + delimiter = ')' + matched.group(2) + '"' + + end = matched.group(3).find(delimiter) + if end >= 0: + # Raw string ended on same line + line = (matched.group(1) + '""' + + matched.group(3)[end + len(delimiter):]) + delimiter = None + else: + # Start of a multi-line raw string + line = matched.group(1) + '""' + else: + break + + lines_without_raw_strings.append(line) + + # TODO(unknown): if delimiter is not None here, we might want to + # emit a warning for unterminated string. + return lines_without_raw_strings + + +def FindNextMultiLineCommentStart(lines, lineix): + """Find the beginning marker for a multiline comment.""" + while lineix < len(lines): + if lines[lineix].strip().startswith('/*'): + # Only return this marker if the comment goes beyond this line + if lines[lineix].strip().find('*/', 2) < 0: + return lineix + lineix += 1 + return len(lines) + + +def FindNextMultiLineCommentEnd(lines, lineix): + """We are inside a comment, find the end marker.""" + while lineix < len(lines): + if lines[lineix].strip().endswith('*/'): + return lineix + lineix += 1 + return len(lines) + + +def RemoveMultiLineCommentsFromRange(lines, begin, end): + """Clears a range of lines for multi-line comments.""" + # Having // dummy comments makes the lines non-empty, so we will not get + # unnecessary blank line warnings later in the code. + for i in range(begin, end): + lines[i] = '/**/' + + +def RemoveMultiLineComments(filename, lines, error): + """Removes multiline (c-style) comments from lines.""" + lineix = 0 + while lineix < len(lines): + lineix_begin = FindNextMultiLineCommentStart(lines, lineix) + if lineix_begin >= len(lines): + return + lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) + if lineix_end >= len(lines): + error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, + 'Could not find end of multi-line comment') + return + RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) + lineix = lineix_end + 1 + + +def CleanseComments(line): + """Removes //-comments and single-line C-style /* */ comments. + + Args: + line: A line of C++ source. + + Returns: + The line with single-line comments removed. + """ + commentpos = line.find('//') + if commentpos != -1 and not IsCppString(line[:commentpos]): + line = line[:commentpos].rstrip() + # get rid of /* ... */ + return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) + + +class CleansedLines(object): + """Holds 4 copies of all lines with different preprocessing applied to them. + + 1) elided member contains lines without strings and comments. + 2) lines member contains lines without comments. + 3) raw_lines member contains all the lines without processing. + 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw + strings removed. + All these members are of , and of the same length. + """ + + def __init__(self, lines): + self.elided = [] + self.lines = [] + self.raw_lines = lines + self.num_lines = len(lines) + self.lines_without_raw_strings = CleanseRawStrings(lines) + for linenum in range(len(self.lines_without_raw_strings)): + self.lines.append(CleanseComments( + self.lines_without_raw_strings[linenum])) + elided = self._CollapseStrings(self.lines_without_raw_strings[linenum]) + self.elided.append(CleanseComments(elided)) + + def NumLines(self): + """Returns the number of lines represented.""" + return self.num_lines + + @staticmethod + def _CollapseStrings(elided): + """Collapses strings and chars on a line to simple "" or '' blocks. + + We nix strings first so we're not fooled by text like '"http://"' + + Args: + elided: The line being processed. + + Returns: + The line with collapsed strings. + """ + if _RE_PATTERN_INCLUDE.match(elided): + return elided + + # Remove escaped characters first to make quote/single quote collapsing + # basic. Things that look like escaped characters shouldn't occur + # outside of strings and chars. + elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) + + # Replace quoted strings and digit separators. Both single quotes + # and double quotes are processed in the same loop, otherwise + # nested quotes wouldn't work. + collapsed = '' + while True: + # Find the first quote character + match = Match(r'^([^\'"]*)([\'"])(.*)$', elided) + if not match: + collapsed += elided + break + head, quote, tail = match.groups() + + if quote == '"': + # Collapse double quoted strings + second_quote = tail.find('"') + if second_quote >= 0: + collapsed += head + '""' + elided = tail[second_quote + 1:] + else: + # Unmatched double quote, don't bother processing the rest + # of the line since this is probably a multiline string. + collapsed += elided + break + else: + # Found single quote, check nearby text to eliminate digit separators. + # + # There is no special handling for floating point here, because + # the integer/fractional/exponent parts would all be parsed + # correctly as long as there are digits on both sides of the + # separator. So we are fine as long as we don't see something + # like "0.'3" (gcc 4.9.0 will not allow this literal). + if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head): + match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail) + collapsed += head + match_literal.group(1).replace("'", '') + elided = match_literal.group(2) + else: + second_quote = tail.find('\'') + if second_quote >= 0: + collapsed += head + "''" + elided = tail[second_quote + 1:] + else: + # Unmatched single quote + collapsed += elided + break + + return collapsed + + +def FindEndOfExpressionInLine(line, startpos, stack): + """Find the position just after the end of current parenthesized expression. + + Args: + line: a CleansedLines line. + startpos: start searching at this position. + stack: nesting stack at startpos. + + Returns: + On finding matching end: (index just after matching end, None) + On finding an unclosed expression: (-1, None) + Otherwise: (-1, new stack at end of this line) + """ + for i in xrange(startpos, len(line)): + char = line[i] + if char in '([{': + # Found start of parenthesized expression, push to expression stack + stack.append(char) + elif char == '<': + # Found potential start of template argument list + if i > 0 and line[i - 1] == '<': + # Left shift operator + if stack and stack[-1] == '<': + stack.pop() + if not stack: + return (-1, None) + elif i > 0 and Search(r'\boperator\s*$', line[0:i]): + # operator<, don't add to stack + continue + else: + # Tentative start of template argument list + stack.append('<') + elif char in ')]}': + # Found end of parenthesized expression. + # + # If we are currently expecting a matching '>', the pending '<' + # must have been an operator. Remove them from expression stack. + while stack and stack[-1] == '<': + stack.pop() + if not stack: + return (-1, None) + if ((stack[-1] == '(' and char == ')') or + (stack[-1] == '[' and char == ']') or + (stack[-1] == '{' and char == '}')): + stack.pop() + if not stack: + return (i + 1, None) + else: + # Mismatched parentheses + return (-1, None) + elif char == '>': + # Found potential end of template argument list. + + # Ignore "->" and operator functions + if (i > 0 and + (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))): + continue + + # Pop the stack if there is a matching '<'. Otherwise, ignore + # this '>' since it must be an operator. + if stack: + if stack[-1] == '<': + stack.pop() + if not stack: + return (i + 1, None) + elif char == ';': + # Found something that look like end of statements. If we are currently + # expecting a '>', the matching '<' must have been an operator, since + # template argument list should not contain statements. + while stack and stack[-1] == '<': + stack.pop() + if not stack: + return (-1, None) + + # Did not find end of expression or unbalanced parentheses on this line + return (-1, stack) + + +def CloseExpression(clean_lines, linenum, pos): + """If input points to ( or { or [ or <, finds the position that closes it. + + If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the + linenum/pos that correspond to the closing of the expression. + + TODO(unknown): cpplint spends a fair bit of time matching parentheses. + Ideally we would want to index all opening and closing parentheses once + and have CloseExpression be just a simple lookup, but due to preprocessor + tricks, this is not so easy. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + pos: A position on the line. + + Returns: + A tuple (line, linenum, pos) pointer *past* the closing brace, or + (line, len(lines), -1) if we never find a close. Note we ignore + strings and comments when matching; and the line we return is the + 'cleansed' line at linenum. + """ + + line = clean_lines.elided[linenum] + if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]): + return (line, clean_lines.NumLines(), -1) + + # Check first line + (end_pos, stack) = FindEndOfExpressionInLine(line, pos, []) + if end_pos > -1: + return (line, linenum, end_pos) + + # Continue scanning forward + while stack and linenum < clean_lines.NumLines() - 1: + linenum += 1 + line = clean_lines.elided[linenum] + (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack) + if end_pos > -1: + return (line, linenum, end_pos) + + # Did not find end of expression before end of file, give up + return (line, clean_lines.NumLines(), -1) + + +def FindStartOfExpressionInLine(line, endpos, stack): + """Find position at the matching start of current expression. + + This is almost the reverse of FindEndOfExpressionInLine, but note + that the input position and returned position differs by 1. + + Args: + line: a CleansedLines line. + endpos: start searching at this position. + stack: nesting stack at endpos. + + Returns: + On finding matching start: (index at matching start, None) + On finding an unclosed expression: (-1, None) + Otherwise: (-1, new stack at beginning of this line) + """ + i = endpos + while i >= 0: + char = line[i] + if char in ')]}': + # Found end of expression, push to expression stack + stack.append(char) + elif char == '>': + # Found potential end of template argument list. + # + # Ignore it if it's a "->" or ">=" or "operator>" + if (i > 0 and + (line[i - 1] == '-' or + Match(r'\s>=\s', line[i - 1:]) or + Search(r'\boperator\s*$', line[0:i]))): + i -= 1 + else: + stack.append('>') + elif char == '<': + # Found potential start of template argument list + if i > 0 and line[i - 1] == '<': + # Left shift operator + i -= 1 + else: + # If there is a matching '>', we can pop the expression stack. + # Otherwise, ignore this '<' since it must be an operator. + if stack and stack[-1] == '>': + stack.pop() + if not stack: + return (i, None) + elif char in '([{': + # Found start of expression. + # + # If there are any unmatched '>' on the stack, they must be + # operators. Remove those. + while stack and stack[-1] == '>': + stack.pop() + if not stack: + return (-1, None) + if ((char == '(' and stack[-1] == ')') or + (char == '[' and stack[-1] == ']') or + (char == '{' and stack[-1] == '}')): + stack.pop() + if not stack: + return (i, None) + else: + # Mismatched parentheses + return (-1, None) + elif char == ';': + # Found something that look like end of statements. If we are currently + # expecting a '<', the matching '>' must have been an operator, since + # template argument list should not contain statements. + while stack and stack[-1] == '>': + stack.pop() + if not stack: + return (-1, None) + + i -= 1 + + return (-1, stack) + + +def ReverseCloseExpression(clean_lines, linenum, pos): + """If input points to ) or } or ] or >, finds the position that opens it. + + If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the + linenum/pos that correspond to the opening of the expression. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + pos: A position on the line. + + Returns: + A tuple (line, linenum, pos) pointer *at* the opening brace, or + (line, 0, -1) if we never find the matching opening brace. Note + we ignore strings and comments when matching; and the line we + return is the 'cleansed' line at linenum. + """ + line = clean_lines.elided[linenum] + if line[pos] not in ')}]>': + return (line, 0, -1) + + # Check last line + (start_pos, stack) = FindStartOfExpressionInLine(line, pos, []) + if start_pos > -1: + return (line, linenum, start_pos) + + # Continue scanning backward + while stack and linenum > 0: + linenum -= 1 + line = clean_lines.elided[linenum] + (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack) + if start_pos > -1: + return (line, linenum, start_pos) + + # Did not find start of expression before beginning of file, give up + return (line, 0, -1) + + +def CheckForCopyright(filename, lines, error): + """Logs an error if no Copyright message appears at the top of the file.""" + + # We'll say it should occur by line 10. Don't forget there's a + # dummy line at the front. + for line in xrange(1, min(len(lines), 11)): + if re.search(r'Copyright', lines[line], re.I): break + else: # means no copyright line was found + error(filename, 0, 'legal/copyright', 5, + 'No copyright message found. ' + 'You should have a line: "Copyright [year] "') + + +def GetIndentLevel(line): + """Return the number of leading spaces in line. + + Args: + line: A string to check. + + Returns: + An integer count of leading spaces, possibly zero. + """ + indent = Match(r'^( *)\S', line) + if indent: + return len(indent.group(1)) + else: + return 0 + + +def GetHeaderGuardCPPVariable(filename): + """Returns the CPP variable that should be used as a header guard. + + Args: + filename: The name of a C++ header file. + + Returns: + The CPP variable that should be used as a header guard in the + named file. + + """ + + # Restores original filename in case that cpplint is invoked from Emacs's + # flymake. + filename = re.sub(r'_flymake\.h$', '.h', filename) + filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) + # Replace 'c++' with 'cpp'. + filename = filename.replace('C++', 'cpp').replace('c++', 'cpp') + + fileinfo = FileInfo(filename) + file_path_from_root = fileinfo.RepositoryName() + if _root: + file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) + return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_' + + +def CheckForHeaderGuard(filename, clean_lines, error): + """Checks that the file contains a header guard. + + Logs an error if no #ifndef header guard is present. For other + headers, checks that the full pathname is used. + + Args: + filename: The name of the C++ header file. + clean_lines: A CleansedLines instance containing the file. + error: The function to call with any errors found. + """ + + # Don't check for header guards if there are error suppression + # comments somewhere in this file. + # + # Because this is silencing a warning for a nonexistent line, we + # only support the very specific NOLINT(build/header_guard) syntax, + # and not the general NOLINT or NOLINT(*) syntax. + raw_lines = clean_lines.lines_without_raw_strings + for i in raw_lines: + if Search(r'//\s*NOLINT\(build/header_guard\)', i): + return + + cppvar = GetHeaderGuardCPPVariable(filename) + + ifndef = '' + ifndef_linenum = 0 + define = '' + endif = '' + endif_linenum = 0 + for linenum, line in enumerate(raw_lines): + linesplit = line.split() + if len(linesplit) >= 2: + # find the first occurrence of #ifndef and #define, save arg + if not ifndef and linesplit[0] == '#ifndef': + # set ifndef to the header guard presented on the #ifndef line. + ifndef = linesplit[1] + ifndef_linenum = linenum + if not define and linesplit[0] == '#define': + define = linesplit[1] + # find the last occurrence of #endif, save entire line + if line.startswith('#endif'): + endif = line + endif_linenum = linenum + + if not ifndef or not define or ifndef != define: + error(filename, 0, 'build/header_guard', 5, + 'No #ifndef header guard found, suggested CPP variable is: %s' % + cppvar) + return + + # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ + # for backward compatibility. + if ifndef != cppvar: + error_level = 0 + if ifndef != cppvar + '_': + error_level = 5 + + ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, + error) + error(filename, ifndef_linenum, 'build/header_guard', error_level, + '#ifndef header guard has wrong style, please use: %s' % cppvar) + + # Check for "//" comments on endif line. + ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, + error) + match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif) + if match: + if match.group(1) == '_': + # Issue low severity warning for deprecated double trailing underscore + error(filename, endif_linenum, 'build/header_guard', 0, + '#endif line should be "#endif // %s"' % cppvar) + return + + # Didn't find the corresponding "//" comment. If this file does not + # contain any "//" comments at all, it could be that the compiler + # only wants "/**/" comments, look for those instead. + no_single_line_comments = True + for i in xrange(1, len(raw_lines) - 1): + line = raw_lines[i] + if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line): + no_single_line_comments = False + break + + if no_single_line_comments: + match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif) + if match: + if match.group(1) == '_': + # Low severity warning for double trailing underscore + error(filename, endif_linenum, 'build/header_guard', 0, + '#endif line should be "#endif /* %s */"' % cppvar) + return + + # Didn't find anything + error(filename, endif_linenum, 'build/header_guard', 5, + '#endif line should be "#endif // %s"' % cppvar) + + +def CheckHeaderFileIncluded(filename, include_state, error): + """Logs an error if a .cc file does not include its header.""" + + # Do not check test files + if filename.endswith('_test.cc') or filename.endswith('_unittest.cc'): + return + + fileinfo = FileInfo(filename) + headerfile = filename[0:len(filename) - 2] + 'h' + if not os.path.exists(headerfile): + return + headername = FileInfo(headerfile).RepositoryName() + first_include = 0 + for section_list in include_state.include_list: + for f in section_list: + if headername in f[0] or f[0] in headername: + return + if not first_include: + first_include = f[1] + + error(filename, first_include, 'build/include', 5, + '%s should include its header file %s' % (fileinfo.RepositoryName(), + headername)) + + +def CheckForBadCharacters(filename, lines, error): + """Logs an error for each line containing bad characters. + + Two kinds of bad characters: + + 1. Unicode replacement characters: These indicate that either the file + contained invalid UTF-8 (likely) or Unicode replacement characters (which + it shouldn't). Note that it's possible for this to throw off line + numbering if the invalid UTF-8 occurred adjacent to a newline. + + 2. NUL bytes. These are problematic for some tools. + + Args: + filename: The name of the current file. + lines: An array of strings, each representing a line of the file. + error: The function to call with any errors found. + """ + for linenum, line in enumerate(lines): + if u'\ufffd' in line: + error(filename, linenum, 'readability/utf8', 5, + 'Line contains invalid UTF-8 (or Unicode replacement character).') + if '\0' in line: + error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') + + +def CheckForNewlineAtEOF(filename, lines, error): + """Logs an error if there is no newline char at the end of the file. + + Args: + filename: The name of the current file. + lines: An array of strings, each representing a line of the file. + error: The function to call with any errors found. + """ + + # The array lines() was created by adding two newlines to the + # original file (go figure), then splitting on \n. + # To verify that the file ends in \n, we just have to make sure the + # last-but-two element of lines() exists and is empty. + if len(lines) < 3 or lines[-2]: + error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, + 'Could not find a newline character at the end of the file.') + + +def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): + """Logs an error if we see /* ... */ or "..." that extend past one line. + + /* ... */ comments are legit inside macros, for one line. + Otherwise, we prefer // comments, so it's ok to warn about the + other. Likewise, it's ok for strings to extend across multiple + lines, as long as a line continuation character (backslash) + terminates each line. Although not currently prohibited by the C++ + style guide, it's ugly and unnecessary. We don't do well with either + in this lint program, so we warn about both. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Remove all \\ (escaped backslashes) from the line. They are OK, and the + # second (escaped) slash may trigger later \" detection erroneously. + line = line.replace('\\\\', '') + + if line.count('/*') > line.count('*/'): + error(filename, linenum, 'readability/multiline_comment', 5, + 'Complex multi-line /*...*/-style comment found. ' + 'Lint may give bogus warnings. ' + 'Consider replacing these with //-style comments, ' + 'with #if 0...#endif, ' + 'or with more clearly structured multi-line comments.') + + if (line.count('"') - line.count('\\"')) % 2: + error(filename, linenum, 'readability/multiline_string', 5, + 'Multi-line string ("...") found. This lint script doesn\'t ' + 'do well with such strings, and may give bogus warnings. ' + 'Use C++11 raw strings or concatenation instead.') + + +# (non-threadsafe name, thread-safe alternative, validation pattern) +# +# The validation pattern is used to eliminate false positives such as: +# _rand(); // false positive due to substring match. +# ->rand(); // some member function rand(). +# ACMRandom rand(seed); // some variable named rand. +# ISAACRandom rand(); // another variable named rand. +# +# Basically we require the return value of these functions to be used +# in some expression context on the same line by matching on some +# operator before the function name. This eliminates constructors and +# member function calls. +_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)' +_THREADING_LIST = ( + ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'), + ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'), + ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'), + ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'), + ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'), + ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'), + ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'), + ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'), + ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'), + ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'), + ('strtok(', 'strtok_r(', + _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'), + ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'), + ) + + +def CheckPosixThreading(filename, clean_lines, linenum, error): + """Checks for calls to thread-unsafe functions. + + Much code has been originally written without consideration of + multi-threading. Also, engineers are relying on their old experience; + they have learned posix before threading extensions were added. These + tests guide the engineers to use thread-safe functions (when using + posix directly). + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST: + # Additional pattern matching check to confirm that this is the + # function we are looking for + if Search(pattern, line): + error(filename, linenum, 'runtime/threadsafe_fn', 2, + 'Consider using ' + multithread_safe_func + + '...) instead of ' + single_thread_func + + '...) for improved thread safety.') + + +def CheckVlogArguments(filename, clean_lines, linenum, error): + """Checks that VLOG() is only used for defining a logging level. + + For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and + VLOG(FATAL) are not. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): + error(filename, linenum, 'runtime/vlog', 5, + 'VLOG() should be used with numeric verbosity level. ' + 'Use LOG() if you want symbolic severity levels.') + +# Matches invalid increment: *count++, which moves pointer instead of +# incrementing a value. +_RE_PATTERN_INVALID_INCREMENT = re.compile( + r'^\s*\*\w+(\+\+|--);') + + +def CheckInvalidIncrement(filename, clean_lines, linenum, error): + """Checks for invalid increment *count++. + + For example following function: + void increment_counter(int* count) { + *count++; + } + is invalid, because it effectively does count++, moving pointer, and should + be replaced with ++*count, (*count)++ or *count += 1. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + if _RE_PATTERN_INVALID_INCREMENT.match(line): + error(filename, linenum, 'runtime/invalid_increment', 5, + 'Changing pointer instead of value (or unused value of operator*).') + + +def IsMacroDefinition(clean_lines, linenum): + if Search(r'^#define', clean_lines[linenum]): + return True + + if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]): + return True + + return False + + +def IsForwardClassDeclaration(clean_lines, linenum): + return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum]) + + +class _BlockInfo(object): + """Stores information about a generic block of code.""" + + def __init__(self, seen_open_brace): + self.seen_open_brace = seen_open_brace + self.open_parentheses = 0 + self.inline_asm = _NO_ASM + self.check_namespace_indentation = False + + def CheckBegin(self, filename, clean_lines, linenum, error): + """Run checks that applies to text up to the opening brace. + + This is mostly for checking the text after the class identifier + and the "{", usually where the base class is specified. For other + blocks, there isn't much to check, so we always pass. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + pass + + def CheckEnd(self, filename, clean_lines, linenum, error): + """Run checks that applies to text after the closing brace. + + This is mostly used for checking end of namespace comments. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + pass + + def IsBlockInfo(self): + """Returns true if this block is a _BlockInfo. + + This is convenient for verifying that an object is an instance of + a _BlockInfo, but not an instance of any of the derived classes. + + Returns: + True for this class, False for derived classes. + """ + return self.__class__ == _BlockInfo + + +class _ExternCInfo(_BlockInfo): + """Stores information about an 'extern "C"' block.""" + + def __init__(self): + _BlockInfo.__init__(self, True) + + +class _ClassInfo(_BlockInfo): + """Stores information about a class.""" + + def __init__(self, name, class_or_struct, clean_lines, linenum): + _BlockInfo.__init__(self, False) + self.name = name + self.starting_linenum = linenum + self.is_derived = False + self.check_namespace_indentation = True + if class_or_struct == 'struct': + self.access = 'public' + self.is_struct = True + else: + self.access = 'private' + self.is_struct = False + + # Remember initial indentation level for this class. Using raw_lines here + # instead of elided to account for leading comments. + self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum]) + + # Try to find the end of the class. This will be confused by things like: + # class A { + # } *x = { ... + # + # But it's still good enough for CheckSectionSpacing. + self.last_line = 0 + depth = 0 + for i in range(linenum, clean_lines.NumLines()): + line = clean_lines.elided[i] + depth += line.count('{') - line.count('}') + if not depth: + self.last_line = i + break + + def CheckBegin(self, filename, clean_lines, linenum, error): + # Look for a bare ':' + if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): + self.is_derived = True + + def CheckEnd(self, filename, clean_lines, linenum, error): + # If there is a DISALLOW macro, it should appear near the end of + # the class. + seen_last_thing_in_class = False + for i in xrange(linenum - 1, self.starting_linenum, -1): + match = Search( + r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' + + self.name + r'\)', + clean_lines.elided[i]) + if match: + if seen_last_thing_in_class: + error(filename, i, 'readability/constructors', 3, + match.group(1) + ' should be the last thing in the class') + break + + if not Match(r'^\s*$', clean_lines.elided[i]): + seen_last_thing_in_class = True + + # Check that closing brace is aligned with beginning of the class. + # Only do this if the closing brace is indented by only whitespaces. + # This means we will not check single-line class definitions. + indent = Match(r'^( *)\}', clean_lines.elided[linenum]) + if indent and len(indent.group(1)) != self.class_indent: + if self.is_struct: + parent = 'struct ' + self.name + else: + parent = 'class ' + self.name + error(filename, linenum, 'whitespace/indent', 3, + 'Closing brace should be aligned with beginning of %s' % parent) + + +class _NamespaceInfo(_BlockInfo): + """Stores information about a namespace.""" + + def __init__(self, name, linenum): + _BlockInfo.__init__(self, False) + self.name = name or '' + self.starting_linenum = linenum + self.check_namespace_indentation = True + + def CheckEnd(self, filename, clean_lines, linenum, error): + """Check end of namespace comments.""" + line = clean_lines.raw_lines[linenum] + + # Check how many lines is enclosed in this namespace. Don't issue + # warning for missing namespace comments if there aren't enough + # lines. However, do apply checks if there is already an end of + # namespace comment and it's incorrect. + # + # TODO(unknown): We always want to check end of namespace comments + # if a namespace is large, but sometimes we also want to apply the + # check if a short namespace contained nontrivial things (something + # other than forward declarations). There is currently no logic on + # deciding what these nontrivial things are, so this check is + # triggered by namespace size only, which works most of the time. + if (linenum - self.starting_linenum < 10 + and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)): + return + + # Look for matching comment at end of namespace. + # + # Note that we accept C style "/* */" comments for terminating + # namespaces, so that code that terminate namespaces inside + # preprocessor macros can be cpplint clean. + # + # We also accept stuff like "// end of namespace ." with the + # period at the end. + # + # Besides these, we don't accept anything else, otherwise we might + # get false negatives when existing comment is a substring of the + # expected namespace. + if self.name: + # Named namespace + if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + + r'[\*/\.\\\s]*$'), + line): + error(filename, linenum, 'readability/namespace', 5, + 'Namespace should be terminated with "// namespace %s"' % + self.name) + else: + # Anonymous namespace + if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): + # If "// namespace anonymous" or "// anonymous namespace (more text)", + # mention "// anonymous namespace" as an acceptable form + if Match(r'}.*\b(namespace anonymous|anonymous namespace)\b', line): + error(filename, linenum, 'readability/namespace', 5, + 'Anonymous namespace should be terminated with "// namespace"' + ' or "// anonymous namespace"') + else: + error(filename, linenum, 'readability/namespace', 5, + 'Anonymous namespace should be terminated with "// namespace"') + + +class _PreprocessorInfo(object): + """Stores checkpoints of nesting stacks when #if/#else is seen.""" + + def __init__(self, stack_before_if): + # The entire nesting stack before #if + self.stack_before_if = stack_before_if + + # The entire nesting stack up to #else + self.stack_before_else = [] + + # Whether we have already seen #else or #elif + self.seen_else = False + + +class NestingState(object): + """Holds states related to parsing braces.""" + + def __init__(self): + # Stack for tracking all braces. An object is pushed whenever we + # see a "{", and popped when we see a "}". Only 3 types of + # objects are possible: + # - _ClassInfo: a class or struct. + # - _NamespaceInfo: a namespace. + # - _BlockInfo: some other type of block. + self.stack = [] + + # Top of the previous stack before each Update(). + # + # Because the nesting_stack is updated at the end of each line, we + # had to do some convoluted checks to find out what is the current + # scope at the beginning of the line. This check is simplified by + # saving the previous top of nesting stack. + # + # We could save the full stack, but we only need the top. Copying + # the full nesting stack would slow down cpplint by ~10%. + self.previous_stack_top = [] + + # Stack of _PreprocessorInfo objects. + self.pp_stack = [] + + def SeenOpenBrace(self): + """Check if we have seen the opening brace for the innermost block. + + Returns: + True if we have seen the opening brace, False if the innermost + block is still expecting an opening brace. + """ + return (not self.stack) or self.stack[-1].seen_open_brace + + def InNamespaceBody(self): + """Check if we are currently one level inside a namespace body. + + Returns: + True if top of the stack is a namespace block, False otherwise. + """ + return self.stack and isinstance(self.stack[-1], _NamespaceInfo) + + def InExternC(self): + """Check if we are currently one level inside an 'extern "C"' block. + + Returns: + True if top of the stack is an extern block, False otherwise. + """ + return self.stack and isinstance(self.stack[-1], _ExternCInfo) + + def InClassDeclaration(self): + """Check if we are currently one level inside a class or struct declaration. + + Returns: + True if top of the stack is a class/struct, False otherwise. + """ + return self.stack and isinstance(self.stack[-1], _ClassInfo) + + def InAsmBlock(self): + """Check if we are currently one level inside an inline ASM block. + + Returns: + True if the top of the stack is a block containing inline ASM. + """ + return self.stack and self.stack[-1].inline_asm != _NO_ASM + + def InTemplateArgumentList(self, clean_lines, linenum, pos): + """Check if current position is inside template argument list. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + pos: position just after the suspected template argument. + Returns: + True if (linenum, pos) is inside template arguments. + """ + while linenum < clean_lines.NumLines(): + # Find the earliest character that might indicate a template argument + line = clean_lines.elided[linenum] + match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:]) + if not match: + linenum += 1 + pos = 0 + continue + token = match.group(1) + pos += len(match.group(0)) + + # These things do not look like template argument list: + # class Suspect { + # class Suspect x; } + if token in ('{', '}', ';'): return False + + # These things look like template argument list: + # template + # template + # template + # template + if token in ('>', '=', '[', ']', '.'): return True + + # Check if token is an unmatched '<'. + # If not, move on to the next character. + if token != '<': + pos += 1 + if pos >= len(line): + linenum += 1 + pos = 0 + continue + + # We can't be sure if we just find a single '<', and need to + # find the matching '>'. + (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1) + if end_pos < 0: + # Not sure if template argument list or syntax error in file + return False + linenum = end_line + pos = end_pos + return False + + def UpdatePreprocessor(self, line): + """Update preprocessor stack. + + We need to handle preprocessors due to classes like this: + #ifdef SWIG + struct ResultDetailsPageElementExtensionPoint { + #else + struct ResultDetailsPageElementExtensionPoint : public Extension { + #endif + + We make the following assumptions (good enough for most files): + - Preprocessor condition evaluates to true from #if up to first + #else/#elif/#endif. + + - Preprocessor condition evaluates to false from #else/#elif up + to #endif. We still perform lint checks on these lines, but + these do not affect nesting stack. + + Args: + line: current line to check. + """ + if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): + # Beginning of #if block, save the nesting stack here. The saved + # stack will allow us to restore the parsing state in the #else case. + self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) + elif Match(r'^\s*#\s*(else|elif)\b', line): + # Beginning of #else block + if self.pp_stack: + if not self.pp_stack[-1].seen_else: + # This is the first #else or #elif block. Remember the + # whole nesting stack up to this point. This is what we + # keep after the #endif. + self.pp_stack[-1].seen_else = True + self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) + + # Restore the stack to how it was before the #if + self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) + else: + # TODO(unknown): unexpected #else, issue warning? + pass + elif Match(r'^\s*#\s*endif\b', line): + # End of #if or #else blocks. + if self.pp_stack: + # If we saw an #else, we will need to restore the nesting + # stack to its former state before the #else, otherwise we + # will just continue from where we left off. + if self.pp_stack[-1].seen_else: + # Here we can just use a shallow copy since we are the last + # reference to it. + self.stack = self.pp_stack[-1].stack_before_else + # Drop the corresponding #if + self.pp_stack.pop() + else: + # TODO(unknown): unexpected #endif, issue warning? + pass + + # TODO(unknown): Update() is too long, but we will refactor later. + def Update(self, filename, clean_lines, linenum, error): + """Update nesting state with current line. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Remember top of the previous nesting stack. + # + # The stack is always pushed/popped and not modified in place, so + # we can just do a shallow copy instead of copy.deepcopy. Using + # deepcopy would slow down cpplint by ~28%. + if self.stack: + self.previous_stack_top = self.stack[-1] + else: + self.previous_stack_top = None + + # Update pp_stack + self.UpdatePreprocessor(line) + + # Count parentheses. This is to avoid adding struct arguments to + # the nesting stack. + if self.stack: + inner_block = self.stack[-1] + depth_change = line.count('(') - line.count(')') + inner_block.open_parentheses += depth_change + + # Also check if we are starting or ending an inline assembly block. + if inner_block.inline_asm in (_NO_ASM, _END_ASM): + if (depth_change != 0 and + inner_block.open_parentheses == 1 and + _MATCH_ASM.match(line)): + # Enter assembly block + inner_block.inline_asm = _INSIDE_ASM + else: + # Not entering assembly block. If previous line was _END_ASM, + # we will now shift to _NO_ASM state. + inner_block.inline_asm = _NO_ASM + elif (inner_block.inline_asm == _INSIDE_ASM and + inner_block.open_parentheses == 0): + # Exit assembly block + inner_block.inline_asm = _END_ASM + + # Consume namespace declaration at the beginning of the line. Do + # this in a loop so that we catch same line declarations like this: + # namespace proto2 { namespace bridge { class MessageSet; } } + while True: + # Match start of namespace. The "\b\s*" below catches namespace + # declarations even if it weren't followed by a whitespace, this + # is so that we don't confuse our namespace checker. The + # missing spaces will be flagged by CheckSpacing. + namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) + if not namespace_decl_match: + break + + new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) + self.stack.append(new_namespace) + + line = namespace_decl_match.group(2) + if line.find('{') != -1: + new_namespace.seen_open_brace = True + line = line[line.find('{') + 1:] + + # Look for a class declaration in whatever is left of the line + # after parsing namespaces. The regexp accounts for decorated classes + # such as in: + # class LOCKABLE API Object { + # }; + class_decl_match = Match( + r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?' + r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))' + r'(.*)$', line) + if (class_decl_match and + (not self.stack or self.stack[-1].open_parentheses == 0)): + # We do not want to accept classes that are actually template arguments: + # template , + # template class Ignore3> + # void Function() {}; + # + # To avoid template argument cases, we scan forward and look for + # an unmatched '>'. If we see one, assume we are inside a + # template argument list. + end_declaration = len(class_decl_match.group(1)) + if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration): + self.stack.append(_ClassInfo( + class_decl_match.group(3), class_decl_match.group(2), + clean_lines, linenum)) + line = class_decl_match.group(4) + + # If we have not yet seen the opening brace for the innermost block, + # run checks here. + if not self.SeenOpenBrace(): + self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) + + # Update access control if we are inside a class/struct + if self.stack and isinstance(self.stack[-1], _ClassInfo): + classinfo = self.stack[-1] + access_match = Match( + r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' + r':(?:[^:]|$)', + line) + if access_match: + classinfo.access = access_match.group(2) + + # Check that access keywords are indented +1 space. Skip this + # check if the keywords are not preceded by whitespaces. + indent = access_match.group(1) + if (len(indent) != classinfo.class_indent + 1 and + Match(r'^\s*$', indent)): + if classinfo.is_struct: + parent = 'struct ' + classinfo.name + else: + parent = 'class ' + classinfo.name + slots = '' + if access_match.group(3): + slots = access_match.group(3) + error(filename, linenum, 'whitespace/indent', 3, + '%s%s: should be indented +1 space inside %s' % ( + access_match.group(2), slots, parent)) + + # Consume braces or semicolons from what's left of the line + while True: + # Match first brace, semicolon, or closed parenthesis. + matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) + if not matched: + break + + token = matched.group(1) + if token == '{': + # If namespace or class hasn't seen a opening brace yet, mark + # namespace/class head as complete. Push a new block onto the + # stack otherwise. + if not self.SeenOpenBrace(): + self.stack[-1].seen_open_brace = True + elif Match(r'^extern\s*"[^"]*"\s*\{', line): + self.stack.append(_ExternCInfo()) + else: + self.stack.append(_BlockInfo(True)) + if _MATCH_ASM.match(line): + self.stack[-1].inline_asm = _BLOCK_ASM + + elif token == ';' or token == ')': + # If we haven't seen an opening brace yet, but we already saw + # a semicolon, this is probably a forward declaration. Pop + # the stack for these. + # + # Similarly, if we haven't seen an opening brace yet, but we + # already saw a closing parenthesis, then these are probably + # function arguments with extra "class" or "struct" keywords. + # Also pop these stack for these. + if not self.SeenOpenBrace(): + self.stack.pop() + else: # token == '}' + # Perform end of block checks and pop the stack. + if self.stack: + self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) + self.stack.pop() + line = matched.group(2) + + def InnermostClass(self): + """Get class info on the top of the stack. + + Returns: + A _ClassInfo object if we are inside a class, or None otherwise. + """ + for i in range(len(self.stack), 0, -1): + classinfo = self.stack[i - 1] + if isinstance(classinfo, _ClassInfo): + return classinfo + return None + + def CheckCompletedBlocks(self, filename, error): + """Checks that all classes and namespaces have been completely parsed. + + Call this when all lines in a file have been processed. + Args: + filename: The name of the current file. + error: The function to call with any errors found. + """ + # Note: This test can result in false positives if #ifdef constructs + # get in the way of brace matching. See the testBuildClass test in + # cpplint_unittest.py for an example of this. + for obj in self.stack: + if isinstance(obj, _ClassInfo): + error(filename, obj.starting_linenum, 'build/class', 5, + 'Failed to find complete declaration of class %s' % + obj.name) + elif isinstance(obj, _NamespaceInfo): + error(filename, obj.starting_linenum, 'build/namespaces', 5, + 'Failed to find complete declaration of namespace %s' % + obj.name) + + +def CheckForNonStandardConstructs(filename, clean_lines, linenum, + nesting_state, error): + r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. + + Complain about several constructs which gcc-2 accepts, but which are + not standard C++. Warning about these in lint is one way to ease the + transition to new compilers. + - put storage class first (e.g. "static const" instead of "const static"). + - "%lld" instead of %qd" in printf-type functions. + - "%1$d" is non-standard in printf-type functions. + - "\%" is an undefined character escape sequence. + - text after #endif is not allowed. + - invalid inner-style forward declaration. + - >? and ?= and )\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', + line): + error(filename, linenum, 'build/deprecated', 3, + '>? and ))?' + # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' + error(filename, linenum, 'runtime/member_string_references', 2, + 'const string& members are dangerous. It is much better to use ' + 'alternatives, such as pointers or simple constants.') + + # Everything else in this function operates on class declarations. + # Return early if the top of the nesting stack is not a class, or if + # the class head is not completed yet. + classinfo = nesting_state.InnermostClass() + if not classinfo or not classinfo.seen_open_brace: + return + + # The class may have been declared with namespace or classname qualifiers. + # The constructor and destructor will not have those qualifiers. + base_classname = classinfo.name.split('::')[-1] + + # Look for single-argument constructors that aren't marked explicit. + # Technically a valid construct, but against style. Also look for + # non-single-argument constructors which are also technically valid, but + # strongly suggest something is wrong. + explicit_constructor_match = Match( + r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*' + r'\(((?:[^()]|\([^()]*\))*)\)' + % re.escape(base_classname), + line) + + if explicit_constructor_match: + is_marked_explicit = explicit_constructor_match.group(1) + + if not explicit_constructor_match.group(2): + constructor_args = [] + else: + constructor_args = explicit_constructor_match.group(2).split(',') + + # collapse arguments so that commas in template parameter lists and function + # argument parameter lists don't split arguments in two + i = 0 + while i < len(constructor_args): + constructor_arg = constructor_args[i] + while (constructor_arg.count('<') > constructor_arg.count('>') or + constructor_arg.count('(') > constructor_arg.count(')')): + constructor_arg += ',' + constructor_args[i + 1] + del constructor_args[i + 1] + constructor_args[i] = constructor_arg + i += 1 + + defaulted_args = [arg for arg in constructor_args if '=' in arg] + noarg_constructor = (not constructor_args or # empty arg list + # 'void' arg specifier + (len(constructor_args) == 1 and + constructor_args[0].strip() == 'void')) + onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg + not noarg_constructor) or + # all but at most one arg defaulted + (len(constructor_args) >= 1 and + not noarg_constructor and + len(defaulted_args) >= len(constructor_args) - 1)) + initializer_list_constructor = bool( + onearg_constructor and + Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0])) + copy_constructor = bool( + onearg_constructor and + Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&' + % re.escape(base_classname), constructor_args[0].strip())) + + if (not is_marked_explicit and + onearg_constructor and + not initializer_list_constructor and + not copy_constructor): + if defaulted_args: + error(filename, linenum, 'runtime/explicit', 5, + 'Constructors callable with one argument ' + 'should be marked explicit.') + else: + error(filename, linenum, 'runtime/explicit', 5, + 'Single-parameter constructors should be marked explicit.') + elif is_marked_explicit and not onearg_constructor: + if noarg_constructor: + error(filename, linenum, 'runtime/explicit', 5, + 'Zero-parameter constructors should not be marked explicit.') + else: + error(filename, linenum, 'runtime/explicit', 0, + 'Constructors that require multiple arguments ' + 'should not be marked explicit.') + + +def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): + """Checks for the correctness of various spacing around function calls. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Since function calls often occur inside if/for/while/switch + # expressions - which have their own, more liberal conventions - we + # first see if we should be looking inside such an expression for a + # function call, to which we can apply more strict standards. + fncall = line # if there's no control flow construct, look at whole line + for pattern in (r'\bif\s*\((.*)\)\s*{', + r'\bfor\s*\((.*)\)\s*{', + r'\bwhile\s*\((.*)\)\s*[{;]', + r'\bswitch\s*\((.*)\)\s*{'): + match = Search(pattern, line) + if match: + fncall = match.group(1) # look inside the parens for function calls + break + + # Except in if/for/while/switch, there should never be space + # immediately inside parens (eg "f( 3, 4 )"). We make an exception + # for nested parens ( (a+b) + c ). Likewise, there should never be + # a space before a ( when it's a function argument. I assume it's a + # function argument when the char before the whitespace is legal in + # a function name (alnum + _) and we're not starting a macro. Also ignore + # pointers and references to arrays and functions coz they're too tricky: + # we use a very simple way to recognize these: + # " (something)(maybe-something)" or + # " (something)(maybe-something," or + # " (something)[something]" + # Note that we assume the contents of [] to be short enough that + # they'll never need to wrap. + if ( # Ignore control structures. + not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', + fncall) and + # Ignore pointers/references to functions. + not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and + # Ignore pointers/references to arrays. + not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): + if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call + error(filename, linenum, 'whitespace/parens', 4, + '[SPC_M_SEP]Extra space after ( in function call') + elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): + error(filename, linenum, 'whitespace/parens', 2, + '[SPC_M_SEP]Extra space after (') + if (Search(r'\w\s+\(', fncall) and + not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and + not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and + not Search(r'\bcase\s+\(', fncall)): + # TODO(unknown): Space after an operator function seem to be a common + # error, silence those for now by restricting them to highest verbosity. + if Search(r'\boperator_*\b', line): + error(filename, linenum, 'whitespace/parens', 0, + '[SPC_M_SEP]Extra space before ( in function call') + # exception case for copyright comments by jay.jo + elif (not Search(r'\bCopyright\b', line) and + not Search(r'\bLicensed under\b', line)): + error(filename, linenum, 'whitespace/parens', 4, + '[SPC_M_SEP]Extra space before ( in function call') + # If the ) is followed only by a newline or a { + newline, assume it's + # part of a control statement (if/while/etc), and don't complain + if Search(r'[^)]\s+\)\s*[^{\s]', fncall): + # If the closing parenthesis is preceded by only whitespaces, + # try to give a more descriptive error message. + if Search(r'^\s+\)', fncall): + error(filename, linenum, 'whitespace/parens', 2, + '[SPC_M_SEP]Closing ) should be moved to the previous line') + else: + error(filename, linenum, 'whitespace/parens', 2, + '[SPC_M_SEP]Extra space before )') + + +def IsBlankLine(line): + """Returns true if the given line is blank. + + We consider a line to be blank if the line is empty or consists of + only white spaces. + + Args: + line: A line of a string. + + Returns: + True, if the given line is blank. + """ + return not line or line.isspace() + + +def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, + error): + is_namespace_indent_item = ( + len(nesting_state.stack) > 1 and + nesting_state.stack[-1].check_namespace_indentation and + isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and + nesting_state.previous_stack_top == nesting_state.stack[-2]) + + if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, + clean_lines.elided, line): + CheckItemIndentationInNamespace(filename, clean_lines.elided, + line, error) + + +def CheckForFunctionLengths(filename, clean_lines, linenum, + function_state, error): + """Reports for long function bodies. + + For an overview why this is done, see: + http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions + + Uses a simplistic algorithm assuming other style guidelines + (especially spacing) are followed. + Only checks unindented functions, so class members are unchecked. + Trivial bodies are unchecked, so constructors with huge initializer lists + may be missed. + Blank/comment lines are not counted so as to avoid encouraging the removal + of vertical space and comments just to get through a lint check. + NOLINT *on the last line of a function* disables this check. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + function_state: Current function name and lines in body so far. + error: The function to call with any errors found. + """ + lines = clean_lines.lines + line = lines[linenum] + joined_line = '' + + starting_func = False + regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... + match_result = Match(regexp, line) + if match_result: + # If the name is all caps and underscores, figure it's a macro and + # ignore it, unless it's TEST or TEST_F. + function_name = match_result.group(1).split()[-1] + if function_name == 'TEST' or function_name == 'TEST_F' or ( + not Match(r'[A-Z_]+$', function_name)): + starting_func = True + + if starting_func: + body_found = False + for start_linenum in xrange(linenum, clean_lines.NumLines()): + start_line = lines[start_linenum] + joined_line += ' ' + start_line.lstrip() + if Search(r'(;|})', start_line): # Declarations and trivial functions + body_found = True + break # ... ignore + elif Search(r'{', start_line): + body_found = True + function = Search(r'((\w|:)*)\(', line).group(1) + if Match(r'TEST', function): # Handle TEST... macros + parameter_regexp = Search(r'(\(.*\))', joined_line) + if parameter_regexp: # Ignore bad syntax + function += parameter_regexp.group(1) + else: + function += '()' + function_state.Begin(function) + break + if not body_found: + # No body for the function (or evidence of a non-function) was found. + error(filename, linenum, 'readability/fn_size', 5, + 'Lint failed to find start of function body.') + elif Match(r'^\}\s*$', line): # function end + function_state.Check(error, filename, linenum) + function_state.End() + elif not Match(r'^\s*$', line): + function_state.Count() # Count non-blank/non-comment lines. + + +_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?') + + +def CheckComment(line, filename, linenum, next_line_start, error): + """Checks for common mistakes in comments. + + Args: + line: The line in question. + filename: The name of the current file. + linenum: The number of the line to check. + next_line_start: The first non-whitespace column of the next line. + error: The function to call with any errors found. + + commentpos = line.find('//') + if commentpos != -1: + # Check if the // may be in quotes. If so, ignore it + # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison + if (line.count('"', 0, commentpos) - + line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes + # Allow one space for new scopes, two spaces otherwise: + if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and + ((commentpos >= 1 and + line[commentpos-1] not in string.whitespace) or + (commentpos >= 2 and + line[commentpos-2] not in string.whitespace))): + error(filename, linenum, 'whitespace/comments', 2, + 'At least two spaces is best between code and comments') + + # Checks for common mistakes in TODO comments. + comment = line[commentpos:] + match = _RE_PATTERN_TODO.match(comment) + if match: + # One whitespace is correct; zero whitespace is handled elsewhere. + leading_whitespace = match.group(1) + if len(leading_whitespace) > 1: + error(filename, linenum, 'whitespace/todo', 2, + 'Too many spaces before TODO') + + username = match.group(2) + if not username: + error(filename, linenum, 'readability/todo', 2, + 'Missing username in TODO; it should look like ' + '"// TODO(my_username): Stuff."') + + middle_whitespace = match.group(3) + # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison + if middle_whitespace != ' ' and middle_whitespace != '': + error(filename, linenum, 'whitespace/todo', 2, + 'TODO(my_username) should be followed by a space') + + # If the comment contains an alphanumeric character, there + # should be a space somewhere between it and the // unless + # it's a /// or //! Doxygen comment. + if (Match(r'//[^ ]*\w', comment) and + not Match(r'(///|//\!)(\s+|$)', comment)): + error(filename, linenum, 'whitespace/comments', 4, + 'Should have a space between // and comment') + +""" +def CheckAccess(filename, clean_lines, linenum, nesting_state, error): + """Checks for improper use of DISALLOW* macros. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] # get rid of comments and strings + + matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' + r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) + if not matched: + return + if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): + if nesting_state.stack[-1].access != 'private': + error(filename, linenum, 'readability/constructors', 3, + '%s must be in the private: section' % matched.group(1)) + + else: + # Found DISALLOW* macro outside a class declaration, or perhaps it + # was used inside a function when it should have been part of the + # class declaration. We could issue a warning here, but it + # probably resulted in a compiler error already. + pass + + +def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): + """Checks for the correctness of various spacing issues in the code. + + Things we check for: spaces around operators, spaces after + if/for/while/switch, no spaces around parens in function calls, two + spaces between code and comment, don't start a block with a blank + line, don't end a function with a blank line, don't add a blank line + after public/protected/private, don't have too many blank lines in a row. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + + # Don't use "elided" lines here, otherwise we can't check commented lines. + # Don't want to use "raw" either, because we don't want to check inside C++11 + # raw strings, + raw = clean_lines.lines_without_raw_strings + line = raw[linenum] + + # Before nixing comments, check if the line is blank for no good + # reason. This includes the first line after a block is opened, and + # blank lines at the end of a function (ie, right before a line like '}' + # + # Skip all the blank line checks if we are immediately inside a + # namespace body. In other words, don't issue blank line warnings + # for this block: + # namespace { + # + # } + # + # A warning about missing end of namespace comments will be issued instead. + # + # Also skip blank line checks for 'extern "C"' blocks, which are formatted + # like namespaces. + if (IsBlankLine(line) and + not nesting_state.InNamespaceBody() and + not nesting_state.InExternC()): + elided = clean_lines.elided + prev_line = elided[linenum - 1] + prevbrace = prev_line.rfind('{') + # TODO(unknown): Don't complain if line before blank line, and line after, + # both start with alnums and are indented the same amount. + # This ignores whitespace at the start of a namespace block + # because those are not usually indented. + if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: + # OK, we have a blank line at the start of a code block. Before we + # complain, we check if it is an exception to the rule: The previous + # non-empty line has the parameters of a function header that are indented + # 4 spaces (because they did not fit in a 80 column line when placed on + # the same line as the function name). We also check for the case where + # the previous line is indented 6 spaces, which may happen when the + # initializers of a constructor do not fit into a 80 column line. + exception = False + if Match(r' {6}\w', prev_line): # Initializer list? + # We are looking for the opening column of initializer list, which + # should be indented 4 spaces to cause 6 space indentation afterwards. + search_position = linenum-2 + while (search_position >= 0 + and Match(r' {6}\w', elided[search_position])): + search_position -= 1 + exception = (search_position >= 0 + and elided[search_position][:5] == ' :') + else: + # Search for the function arguments or an initializer list. We use a + # simple heuristic here: If the line is indented 4 spaces; and we have a + # closing paren, without the opening paren, followed by an opening brace + # or colon (for initializer lists) we assume that it is the last line of + # a function header. If we have a colon indented 4 spaces, it is an + # initializer list. + exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', + prev_line) + or Match(r' {4}:', prev_line)) + + if not exception: + error(filename, linenum, 'whitespace/blank_line', 2, + '[LNE_R_TWS]Redundant blank line at the start of a code block ' + 'should be deleted.') + # Ignore blank lines at the end of a block in a long if-else + # chain, like this: + # if (condition1) { + # // Something followed by a blank line + # + # } else if (condition2) { + # // Something else + # } + if linenum + 1 < clean_lines.NumLines(): + next_line = raw[linenum + 1] + if (next_line + and Match(r'\s*}', next_line) + and next_line.find('} else ') == -1): + error(filename, linenum, 'whitespace/blank_line', 3, + '[LNE_R_TWS]Redundant blank line at the end of a code block ' + 'should be deleted.') + + matched = Match(r'\s*(public|protected|private):', prev_line) + #if matched: + # error(filename, linenum, 'whitespace/blank_line', 3, + # 'Do not leave a blank line after "%s:"' % matched.group(1)) + + # Next, check comments + next_line_start = 0 + if linenum + 1 < clean_lines.NumLines(): + next_line = raw[linenum + 1] + next_line_start = len(next_line) - len(next_line.lstrip()) + CheckComment(line, filename, linenum, next_line_start, error) + + # get rid of comments and strings + line = clean_lines.elided[linenum] + + # You shouldn't have spaces before your brackets, except maybe after + # 'delete []' or 'return []() {};' + if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line): + error(filename, linenum, 'whitespace/braces', 5, + '[SPC_M_SEP]Extra space before [') + + # In range-based for, we wanted spaces before and after the colon, but + # not around "::" tokens that might appear. + if (Search(r'for *\(.*[^:]:[^: ]', line) or + Search(r'for *\(.*[^: ]:[^:]', line)): + error(filename, linenum, 'whitespace/forcolon', 2, + 'Missing space around colon in range-based for loop') + + +def CheckOperatorSpacing(filename, clean_lines, linenum, error): + """Checks for horizontal spacing around operators. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Don't try to do spacing checks for operator methods. Do this by + # replacing the troublesome characters with something else, + # preserving column position for all other characters. + # + # The replacement is done repeatedly to avoid false positives from + # operators that call operators. + while True: + match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line) + if match: + line = match.group(1) + ('_' * len(match.group(2))) + match.group(3) + else: + break + + # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". + # Otherwise not. Note we only check for non-spaces on *both* sides; + # sometimes people put non-spaces on one side when aligning ='s among + # many lines (not that this is behavior that I approve of...) + if ((Search(r'[\w.]=', line) or + Search(r'=[\w.]', line)) + and not Search(r'\b(if|while|for) ', line) + # Operators taken from [lex.operators] in C++11 standard. + and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line) + and not Search(r'operator=', line)): + error(filename, linenum, 'whitespace/operators', 4, + '[SPC_M_OPR]Missing spaces around =') + + # It's ok not to have spaces around binary operators like + - * /, but if + # there's too little whitespace, we get concerned. It's hard to tell, + # though, so we punt on this one for now. TODO. + + # You should always have whitespace around binary operators. + # + # Check <= and >= first to avoid false positives with < and >, then + # check non-include lines for spacing around < and >. + # + # If the operator is followed by a comma, assume it's be used in a + # macro context and don't do any checks. This avoids false + # positives. + # + # Note that && is not included here. Those are checked separately + # in CheckRValueReference + match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line) + if match: + error(filename, linenum, 'whitespace/operators', 3, + '[SPC_M_OPR]Missing spaces around %s' % match.group(1)) + elif not Match(r'#.*include', line): + # Look for < that is not surrounded by spaces. This is only + # triggered if both sides are missing spaces, even though + # technically should should flag if at least one side is missing a + # space. This is done to avoid some false positives with shifts. + match = Match(r'^(.*[^\s<])<[^\s=<,]', line) + if match: + (_, _, end_pos) = CloseExpression( + clean_lines, linenum, len(match.group(1))) + if end_pos <= -1: + error(filename, linenum, 'whitespace/operators', 3, + '[SPC_M_OPR]Missing spaces around <') + + # Look for > that is not surrounded by spaces. Similar to the + # above, we only trigger if both sides are missing spaces to avoid + # false positives with shifts. + match = Match(r'^(.*[^-\s>])>[^\s=>,]', line) + if match: + (_, _, start_pos) = ReverseCloseExpression( + clean_lines, linenum, len(match.group(1))) + if start_pos <= -1: + error(filename, linenum, 'whitespace/operators', 3, + '[SPC_M_OPR]Missing spaces around >') + + # We allow no-spaces around << when used like this: 10<<20, but + # not otherwise (particularly, not when used as streams) + # + # We also allow operators following an opening parenthesis, since + # those tend to be macros that deal with operators. + match = Search(r'(operator|[^\s(<])(?:L|UL|ULL|l|ul|ull)?<<([^\s,=<])', line) + if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and + not (match.group(1) == 'operator' and match.group(2) == ';')): + error(filename, linenum, 'whitespace/operators', 3, + '[SPC_M_OPR]Missing spaces around <<') + + # We allow no-spaces around >> for almost anything. This is because + # C++11 allows ">>" to close nested templates, which accounts for + # most cases when ">>" is not followed by a space. + # + # We still warn on ">>" followed by alpha character, because that is + # likely due to ">>" being used for right shifts, e.g.: + # value >> alpha + # + # When ">>" is used to close templates, the alphanumeric letter that + # follows would be part of an identifier, and there should still be + # a space separating the template type and the identifier. + # type> alpha + match = Search(r'>>[a-zA-Z_]', line) + if match: + error(filename, linenum, 'whitespace/operators', 3, + '[SPC_M_OPR]Missing spaces around >>') + + # There shouldn't be space around unary operators + match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) + if match: + error(filename, linenum, 'whitespace/operators', 4, + '[SPC_M_OPR]Extra space for operator %s' % match.group(1)) + + +def CheckParenthesisSpacing(filename, clean_lines, linenum, error): + """Checks for horizontal spacing around parentheses. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # No spaces after an if, while, switch, or for + match = Search(r' (if\(|for\(|while\(|switch\()', line) + if match: + error(filename, linenum, 'whitespace/parens', 5, + '[SPC_M_SEP]Missing space before ( in %s' % match.group(1)) + + # For if/for/while/switch, the left and right parens should be + # consistent about how many spaces are inside the parens, and + # there should either be zero or one spaces inside the parens. + # We don't want: "if ( foo)" or "if ( foo )". + # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. + match = Search(r'\b(if|for|while|switch)\s*' + r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', + line) + if match: + #if len(match.group(2)) != len(match.group(4)): + # if not (match.group(3) == ';' and + # len(match.group(2)) == 1 + len(match.group(4)) or + # not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): + # error(filename, linenum, 'whitespace/parens', 5, + # 'Mismatching spaces inside () in %s' % match.group(1)) + if len(match.group(2)) not in [0, 1]: + error(filename, linenum, 'whitespace/parens', 5, + '[SPC_M_SEP]Should have zero or one spaces inside ( and ) in %s' % + match.group(1)) + + +def CheckCommaSpacing(filename, clean_lines, linenum, error): + """Checks for horizontal spacing near commas and semicolons. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + raw = clean_lines.lines_without_raw_strings + line = clean_lines.elided[linenum] + + # You should always have a space after a comma (either as fn arg or operator) + # + # This does not apply when the non-space character following the + # comma is another comma, since the only time when that happens is + # for empty macro arguments. + # + # We run this check in two passes: first pass on elided lines to + # verify that lines contain missing whitespaces, second pass on raw + # lines to confirm that those missing whitespaces are not due to + # elided comments. + if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and + Search(r',[^,\s]', raw[linenum])): + error(filename, linenum, 'whitespace/comma', 3, + '[SPC_M_SEP]Missing space after ,') + + # You should always have a space after a semicolon + # except for few corner cases + # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more + # space after ; +# if Search(r';[^\s};\\)/]', line): +# error(filename, linenum, 'whitespace/semicolon', 3, +# 'Missing space after ;') + + +def CheckBracesSpacing(filename, clean_lines, linenum, error): + """Checks for horizontal spacing near commas. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Except after an opening paren, or after another opening brace (in case of + # an initializer list, for instance), you should have spaces before your + # braces. And since you should never have braces at the beginning of a line, + # this is an easy test. + match = Match(r'^(.*[^ ({>]){', line) + if match: + # Try a bit harder to check for brace initialization. This + # happens in one of the following forms: + # Constructor() : initializer_list_{} { ... } + # Constructor{}.MemberFunction() + # Type variable{}; + # FunctionCall(type{}, ...); + # LastArgument(..., type{}); + # LOG(INFO) << type{} << " ..."; + # map_of_type[{...}] = ...; + # ternary = expr ? new type{} : nullptr; + # OuterTemplate{}> + # + # We check for the character following the closing brace, and + # silence the warning if it's one of those listed above, i.e. + # "{.;,)<>]:". + # + # To account for nested initializer list, we allow any number of + # closing braces up to "{;,)<". We can't simply silence the + # warning on first sight of closing brace, because that would + # cause false negatives for things that are not initializer lists. + # Silence this: But not this: + # Outer{ if (...) { + # Inner{...} if (...){ // Missing space before { + # }; } + # + # There is a false negative with this approach if people inserted + # spurious semicolons, e.g. "if (cond){};", but we will catch the + # spurious semicolon with a separate check. + (endline, endlinenum, endpos) = CloseExpression( + clean_lines, linenum, len(match.group(1))) + trailing_text = '' + if endpos > -1: + trailing_text = endline[endpos:] + for offset in xrange(endlinenum + 1, + min(endlinenum + 3, clean_lines.NumLines() - 1)): + trailing_text += clean_lines.elided[offset] + # due to method opening brace false positive, below error has been suppressed + #if not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text): + # error(filename, linenum, 'whitespace/braces', 5, + # '[SPC_M_SEP]Missing space before {') + + # Make sure '} else {' has spaces. + if Search(r'}else', line): + error(filename, linenum, 'whitespace/braces', 5, + '[SPC_M_KWD]Missing space before else') + + # You shouldn't have a space before a semicolon at the end of the line. + # There's a special case for "for" since the style guide allows space before + # the semicolon there. + if Search(r':\s*;\s*$', line): + error(filename, linenum, 'whitespace/semicolon', 5, + 'Semicolon defining empty statement. Use {} instead.') + elif Search(r'^\s*;\s*$', line): + error(filename, linenum, 'whitespace/semicolon', 5, + 'Line contains only semicolon. If this should be an empty statement, ' + 'use {} instead.') + elif (Search(r'\s+;\s*$', line) and + not Search(r'\bfor\b', line)): + error(filename, linenum, 'whitespace/semicolon', 5, + 'Extra space before last semicolon. If this should be an empty ' + 'statement, use {} instead.') + + +def IsDecltype(clean_lines, linenum, column): + """Check if the token ending on (linenum, column) is decltype(). + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: the number of the line to check. + column: end column of the token to check. + Returns: + True if this token is decltype() expression, False otherwise. + """ + (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column) + if start_col < 0: + return False + if Search(r'\bdecltype\s*$', text[0:start_col]): + return True + return False + + +def IsTemplateParameterList(clean_lines, linenum, column): + """Check if the token ending on (linenum, column) is the end of template<>. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: the number of the line to check. + column: end column of the token to check. + Returns: + True if this token is end of a template parameter list, False otherwise. + """ + (_, startline, startpos) = ReverseCloseExpression( + clean_lines, linenum, column) + if (startpos > -1 and + Search(r'\btemplate\s*$', clean_lines.elided[startline][0:startpos])): + return True + return False + + +def IsRValueType(typenames, clean_lines, nesting_state, linenum, column): + """Check if the token ending on (linenum, column) is a type. + + Assumes that text to the right of the column is "&&" or a function + name. + + Args: + typenames: set of type names from template-argument-list. + clean_lines: A CleansedLines instance containing the file. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + linenum: the number of the line to check. + column: end column of the token to check. + Returns: + True if this token is a type, False if we are not sure. + """ + prefix = clean_lines.elided[linenum][0:column] + + # Get one word to the left. If we failed to do so, this is most + # likely not a type, since it's unlikely that the type name and "&&" + # would be split across multiple lines. + match = Match(r'^(.*)(\b\w+|[>*)&])\s*$', prefix) + if not match: + return False + + # Check text following the token. If it's "&&>" or "&&," or "&&...", it's + # most likely a rvalue reference used inside a template. + suffix = clean_lines.elided[linenum][column:] + if Match(r'&&\s*(?:[>,]|\.\.\.)', suffix): + return True + + # Check for known types and end of templates: + # int&& variable + # vector&& variable + # + # Because this function is called recursively, we also need to + # recognize pointer and reference types: + # int* Function() + # int& Function() + if (match.group(2) in typenames or + match.group(2) in ['char', 'char16_t', 'char32_t', 'wchar_t', 'bool', + 'short', 'int', 'long', 'signed', 'unsigned', + 'float', 'double', 'void', 'auto', '>', '*', '&']): + return True + + # If we see a close parenthesis, look for decltype on the other side. + # decltype would unambiguously identify a type, anything else is + # probably a parenthesized expression and not a type. + if match.group(2) == ')': + return IsDecltype( + clean_lines, linenum, len(match.group(1)) + len(match.group(2)) - 1) + + # Check for casts and cv-qualifiers. + # match.group(1) remainder + # -------------- --------- + # const_cast< type&& + # const type&& + # type const&& + if Search(r'\b(?:const_cast\s*<|static_cast\s*<|dynamic_cast\s*<|' + r'reinterpret_cast\s*<|\w+\s)\s*$', + match.group(1)): + return True + + # Look for a preceding symbol that might help differentiate the context. + # These are the cases that would be ambiguous: + # match.group(1) remainder + # -------------- --------- + # Call ( expression && + # Declaration ( type&& + # sizeof ( type&& + # if ( expression && + # while ( expression && + # for ( type&& + # for( ; expression && + # statement ; type&& + # block { type&& + # constructor { expression && + start = linenum + line = match.group(1) + match_symbol = None + while start >= 0: + # We want to skip over identifiers and commas to get to a symbol. + # Commas are skipped so that we can find the opening parenthesis + # for function parameter lists. + match_symbol = Match(r'^(.*)([^\w\s,])[\w\s,]*$', line) + if match_symbol: + break + start -= 1 + line = clean_lines.elided[start] + + if not match_symbol: + # Probably the first statement in the file is an rvalue reference + return True + + if match_symbol.group(2) == '}': + # Found closing brace, probably an indicate of this: + # block{} type&& + return True + + if match_symbol.group(2) == ';': + # Found semicolon, probably one of these: + # for(; expression && + # statement; type&& + + # Look for the previous 'for(' in the previous lines. + before_text = match_symbol.group(1) + for i in xrange(start - 1, max(start - 6, 0), -1): + before_text = clean_lines.elided[i] + before_text + if Search(r'for\s*\([^{};]*$', before_text): + # This is the condition inside a for-loop + return False + + # Did not find a for-init-statement before this semicolon, so this + # is probably a new statement and not a condition. + return True + + if match_symbol.group(2) == '{': + # Found opening brace, probably one of these: + # block{ type&& = ... ; } + # constructor{ expression && expression } + + # Look for a closing brace or a semicolon. If we see a semicolon + # first, this is probably a rvalue reference. + line = clean_lines.elided[start][0:len(match_symbol.group(1)) + 1] + end = start + depth = 1 + while True: + for ch in line: + if ch == ';': + return True + elif ch == '{': + depth += 1 + elif ch == '}': + depth -= 1 + if depth == 0: + return False + end += 1 + if end >= clean_lines.NumLines(): + break + line = clean_lines.elided[end] + # Incomplete program? + return False + + if match_symbol.group(2) == '(': + # Opening parenthesis. Need to check what's to the left of the + # parenthesis. Look back one extra line for additional context. + before_text = match_symbol.group(1) + if linenum > 1: + before_text = clean_lines.elided[linenum - 1] + before_text + before_text = match_symbol.group(1) + + # Patterns that are likely to be types: + # [](type&& + # for (type&& + # sizeof(type&& + # operator=(type&& + # + if Search(r'(?:\]|\bfor|\bsizeof|\boperator\s*\S+\s*)\s*$', before_text): + return True + + # Patterns that are likely to be expressions: + # if (expression && + # while (expression && + # : initializer(expression && + # , initializer(expression && + # ( FunctionCall(expression && + # + FunctionCall(expression && + # + (expression && + # + # The last '+' represents operators such as '+' and '-'. + if Search(r'(?:\bif|\bwhile|[-+=%^(]*>)?\s*$', + match_symbol.group(1)) + if match_func: + # Check for constructors, which don't have return types. + if Search(r'\b(?:explicit|inline)$', match_func.group(1)): + return True + implicit_constructor = Match(r'\s*(\w+)\((?:const\s+)?(\w+)', prefix) + if (implicit_constructor and + implicit_constructor.group(1) == implicit_constructor.group(2)): + return True + return IsRValueType(typenames, clean_lines, nesting_state, linenum, + len(match_func.group(1))) + + # Nothing before the function name. If this is inside a block scope, + # this is probably a function call. + return not (nesting_state.previous_stack_top and + nesting_state.previous_stack_top.IsBlockInfo()) + + if match_symbol.group(2) == '>': + # Possibly a closing bracket, check that what's on the other side + # looks like the start of a template. + return IsTemplateParameterList( + clean_lines, start, len(match_symbol.group(1))) + + # Some other symbol, usually something like "a=b&&c". This is most + # likely not a type. + return False + + +def IsDeletedOrDefault(clean_lines, linenum): + """Check if current constructor or operator is deleted or default. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + Returns: + True if this is a deleted or default constructor. + """ + open_paren = clean_lines.elided[linenum].find('(') + if open_paren < 0: + return False + (close_line, _, close_paren) = CloseExpression( + clean_lines, linenum, open_paren) + if close_paren < 0: + return False + return Match(r'\s*=\s*(?:delete|default)\b', close_line[close_paren:]) + + +def IsRValueAllowed(clean_lines, linenum, typenames): + """Check if RValue reference is allowed on a particular line. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + typenames: set of type names from template-argument-list. + Returns: + True if line is within the region where RValue references are allowed. + """ + # Allow region marked by PUSH/POP macros + for i in xrange(linenum, 0, -1): + line = clean_lines.elided[i] + if Match(r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)', line): + if not line.endswith('PUSH'): + return False + for j in xrange(linenum, clean_lines.NumLines(), 1): + line = clean_lines.elided[j] + if Match(r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)', line): + return line.endswith('POP') + + # Allow operator= + line = clean_lines.elided[linenum] + if Search(r'\boperator\s*=\s*\(', line): + return IsDeletedOrDefault(clean_lines, linenum) + + # Allow constructors + match = Match(r'\s*(?:[\w<>]+::)*([\w<>]+)\s*::\s*([\w<>]+)\s*\(', line) + if match and match.group(1) == match.group(2): + return IsDeletedOrDefault(clean_lines, linenum) + if Search(r'\b(?:explicit|inline)\s+[\w<>]+\s*\(', line): + return IsDeletedOrDefault(clean_lines, linenum) + + if Match(r'\s*[\w<>]+\s*\(', line): + previous_line = 'ReturnType' + if linenum > 0: + previous_line = clean_lines.elided[linenum - 1] + if Match(r'^\s*$', previous_line) or Search(r'[{}:;]\s*$', previous_line): + return IsDeletedOrDefault(clean_lines, linenum) + + # Reject types not mentioned in template-argument-list + while line: + match = Match(r'^.*?(\w+)\s*&&(.*)$', line) + if not match: + break + if match.group(1) not in typenames: + return False + line = match.group(2) + + # All RValue types that were in template-argument-list should have + # been removed by now. Those were allowed, assuming that they will + # be forwarded. + # + # If there are no remaining RValue types left (i.e. types that were + # not found in template-argument-list), flag those as not allowed. + return line.find('&&') < 0 + + +def GetTemplateArgs(clean_lines, linenum): + """Find list of template arguments associated with this function declaration. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: Line number containing the start of the function declaration, + usually one line after the end of the template-argument-list. + Returns: + Set of type names, or empty set if this does not appear to have + any template parameters. + """ + # Find start of function + func_line = linenum + while func_line > 0: + line = clean_lines.elided[func_line] + if Match(r'^\s*$', line): + return set() + if line.find('(') >= 0: + break + func_line -= 1 + if func_line == 0: + return set() + + # Collapse template-argument-list into a single string + argument_list = '' + match = Match(r'^(\s*template\s*)<', clean_lines.elided[func_line]) + if match: + # template-argument-list on the same line as function name + start_col = len(match.group(1)) + _, end_line, end_col = CloseExpression(clean_lines, func_line, start_col) + if end_col > -1 and end_line == func_line: + start_col += 1 # Skip the opening bracket + argument_list = clean_lines.elided[func_line][start_col:end_col] + + elif func_line > 1: + # template-argument-list one line before function name + match = Match(r'^(.*)>\s*$', clean_lines.elided[func_line - 1]) + if match: + end_col = len(match.group(1)) + _, start_line, start_col = ReverseCloseExpression( + clean_lines, func_line - 1, end_col) + if start_col > -1: + start_col += 1 # Skip the opening bracket + while start_line < func_line - 1: + argument_list += clean_lines.elided[start_line][start_col:] + start_col = 0 + start_line += 1 + argument_list += clean_lines.elided[func_line - 1][start_col:end_col] + + if not argument_list: + return set() + + # Extract type names + typenames = set() + while True: + match = Match(r'^[,\s]*(?:typename|class)(?:\.\.\.)?\s+(\w+)(.*)$', + argument_list) + if not match: + break + typenames.add(match.group(1)) + argument_list = match.group(2) + return typenames + + +def CheckRValueReference(filename, clean_lines, linenum, nesting_state, error): + """Check for rvalue references. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + # Find lines missing spaces around &&. + # TODO(unknown): currently we don't check for rvalue references + # with spaces surrounding the && to avoid false positives with + # boolean expressions. + line = clean_lines.elided[linenum] + match = Match(r'^(.*\S)&&', line) + if not match: + match = Match(r'(.*)&&\S', line) + if (not match) or '(&&)' in line or Search(r'\boperator\s*$', match.group(1)): + return + + # Either poorly formed && or an rvalue reference, check the context + # to get a more accurate error message. Mostly we want to determine + # if what's to the left of "&&" is a type or not. + typenames = GetTemplateArgs(clean_lines, linenum) + and_pos = len(match.group(1)) + if IsRValueType(typenames, clean_lines, nesting_state, linenum, and_pos): + if not IsRValueAllowed(clean_lines, linenum, typenames): + error(filename, linenum, 'build/c++11', 3, + 'RValue references are an unapproved C++ feature.') + #else: + # error(filename, linenum, 'whitespace/operators', 3, + # 'Missing spaces around &&') + + +def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): + """Checks for additional blank line issues related to sections. + + Currently the only thing checked here is blank line before protected/private. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + class_info: A _ClassInfo objects. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + # Skip checks if the class is small, where small means 25 lines or less. + # 25 lines seems like a good cutoff since that's the usual height of + # terminals, and any class that can't fit in one screen can't really + # be considered "small". + # + # Also skip checks if we are on the first line. This accounts for + # classes that look like + # class Foo { public: ... }; + # + # If we didn't find the end of the class, last_line would be zero, + # and the check will be skipped by the first condition. + if (class_info.last_line - class_info.starting_linenum <= 24 or + linenum <= class_info.starting_linenum): + return + + matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) + if matched: + # Issue warning if the line before public/protected/private was + # not a blank line, but don't do this if the previous line contains + # "class" or "struct". This can happen two ways: + # - We are at the beginning of the class. + # - We are forward-declaring an inner class that is semantically + # private, but needed to be public for implementation reasons. + # Also ignores cases where the previous line ends with a backslash as can be + # common when defining classes in C macros. + prev_line = clean_lines.lines[linenum - 1] + if (not IsBlankLine(prev_line) and + not Search(r'\b(class|struct)\b', prev_line) and + not Search(r'\\$', prev_line)): + # Try a bit harder to find the beginning of the class. This is to + # account for multi-line base-specifier lists, e.g.: + # class Derived + # : public Base { + end_class_head = class_info.starting_linenum + for i in range(class_info.starting_linenum, linenum): + if Search(r'\{\s*$', clean_lines.lines[i]): + end_class_head = i + break + #if end_class_head < linenum - 1: + # error(filename, linenum, 'whitespace/blank_line', 3, + # '"%s:" should be preceded by a blank line' % matched.group(1)) + + +def GetPreviousNonBlankLine(clean_lines, linenum): + """Return the most recent non-blank line and its line number. + + Args: + clean_lines: A CleansedLines instance containing the file contents. + linenum: The number of the line to check. + + Returns: + A tuple with two elements. The first element is the contents of the last + non-blank line before the current line, or the empty string if this is the + first non-blank line. The second is the line number of that line, or -1 + if this is the first non-blank line. + """ + + prevlinenum = linenum - 1 + while prevlinenum >= 0: + prevline = clean_lines.elided[prevlinenum] + if not IsBlankLine(prevline): # if not a blank line... + return (prevline, prevlinenum) + prevlinenum -= 1 + return ('', -1) + + +def CheckBraces(filename, clean_lines, linenum, error): + """Looks for misplaced braces (e.g. at the end of line). + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + + line = clean_lines.elided[linenum] # get rid of comments and strings + + if Match(r'\s*{\s*$', line): + # We allow an open brace to start a line in the case where someone is using + # braces in a block to explicitly create a new scope, which is commonly used + # to control the lifetime of stack-allocated variables. Braces are also + # used for brace initializers inside function calls. We don't detect this + # perfectly: we just don't complain if the last non-whitespace character on + # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the + # previous line starts a preprocessor block. + prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] + #if (not Search(r'[,;:}{(]\s*$', prevline) and + # not Match(r'\s*#', prevline)): + # error(filename, linenum, 'whitespace/braces', 4, + # '{ should almost always be at the end of the previous line') + + # An else clause should be on the same line as the preceding closing brace. + if Match(r'\s*else\b\s*(?:if\b|\{|$)', line): + prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] + if Match(r'\s*}\s*$', prevline): + error(filename, linenum, 'whitespace/newline', 4, + '[BRC_M_SMT] An else should appear on the same line as the preceding }') + + # If braces come on one side of an else, they should be on both. + # However, we have to worry about "else if" that spans multiple lines! + if Search(r'else if\s*\(', line): # could be multi-line if + brace_on_left = bool(Search(r'}\s*else if\s*\(', line)) + # find the ( after the if + pos = line.find('else if') + pos = line.find('(', pos) + if pos > 0: + (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) + brace_on_right = endline[endpos:].find('{') != -1 + if brace_on_left != brace_on_right: # must be brace after if + error(filename, linenum, 'readability/braces', 5, + '[BRC_M_SMT]If an \'else if\' has a brace on one side, it should have it on both') + elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): + error(filename, linenum, 'readability/braces', 5, + '[BRC_M_SMT]If an \'else\' has a brace on one side, it should have it on both') + + # Likewise, an else should never have the else clause on the same line + #if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): + # error(filename, linenum, 'whitespace/newline', 4, + # 'Else clause should never be on same line as else (use 2 lines)') + + # In the same way, a do/while should never be on one line + #if Match(r'\s*do [^\s{]', line): + # error(filename, linenum, 'whitespace/newline', 4, + # 'do/while clauses should not be on a single line') + + # Check single-line if/else bodies. The style guide says 'curly braces are not + # required for single-line statements'. We additionally allow multi-line, + # single statements, but we reject anything with more than one semicolon in + # it. This means that the first semicolon after the if should be at the end of + # its line, and the line after that should have an indent level equal to or + # lower than the if. We also check for ambiguous if/else nesting without + # braces. + if_else_match = Search(r'\b(if\s*\(|else\b)', line) + if if_else_match and not Match(r'\s*#', line): + if_indent = GetIndentLevel(line) + endline, endlinenum, endpos = line, linenum, if_else_match.end() + if_match = Search(r'\bif\s*\(', line) + if if_match: + # This could be a multiline if condition, so find the end first. + pos = if_match.end() - 1 + (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos) + # Check for an opening brace, either directly after the if or on the next + # line. If found, this isn't a single-statement conditional. + if (not Match(r'\s*{', endline[endpos:]) + and not (Match(r'\s*$', endline[endpos:]) + and endlinenum < (len(clean_lines.elided) - 1) + and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))): + while (endlinenum < len(clean_lines.elided) + and ';' not in clean_lines.elided[endlinenum][endpos:]): + endlinenum += 1 + endpos = 0 + if endlinenum < len(clean_lines.elided): + endline = clean_lines.elided[endlinenum] + # We allow a mix of whitespace and closing braces (e.g. for one-liner + # methods) and a single \ after the semicolon (for macros) + endpos = endline.find(';') + #if not Match(r';[\s}]*(\\?)$', endline[endpos:]): + # Semicolon isn't the last character, there's something trailing. + # Output a warning if the semicolon is not contained inside + # a lambda expression. + #if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$', + # endline): + #error(filename, linenum, 'readability/braces', 4, + # 'If/else bodies with multiple statements require braces') + #elif endlinenum < len(clean_lines.elided) - 1: + # Make sure the next line is dedented + #next_line = clean_lines.elided[endlinenum + 1] + #next_indent = GetIndentLevel(next_line) + # With ambiguous nested if statements, this will error out on the + # if that *doesn't* match the else, regardless of whether it's the + # inner one or outer one. + #if (if_match and Match(r'\s*else\b', next_line) + # and next_indent != if_indent): + # error(filename, linenum, 'readability/braces', 4, + # 'Else clause should be indented at the same level as if. ' + # 'Ambiguous nested if/else chains require braces.') + #elif next_indent > if_indent: + # error(filename, linenum, 'readability/braces', 4, + # 'If/else bodies with multiple statements require braces') + + +def CheckTrailingSemicolon(filename, clean_lines, linenum, error): + """Looks for redundant trailing semicolon. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + + line = clean_lines.elided[linenum] + + # Block bodies should not be followed by a semicolon. Due to C++11 + # brace initialization, there are more places where semicolons are + # required than not, so we use a whitelist approach to check these + # rather than a blacklist. These are the places where "};" should + # be replaced by just "}": + # 1. Some flavor of block following closing parenthesis: + # for (;;) {}; + # while (...) {}; + # switch (...) {}; + # Function(...) {}; + # if (...) {}; + # if (...) else if (...) {}; + # + # 2. else block: + # if (...) else {}; + # + # 3. const member function: + # Function(...) const {}; + # + # 4. Block following some statement: + # x = 42; + # {}; + # + # 5. Block at the beginning of a function: + # Function(...) { + # {}; + # } + # + # Note that naively checking for the preceding "{" will also match + # braces inside multi-dimensional arrays, but this is fine since + # that expression will not contain semicolons. + # + # 6. Block following another block: + # while (true) {} + # {}; + # + # 7. End of namespaces: + # namespace {}; + # + # These semicolons seems far more common than other kinds of + # redundant semicolons, possibly due to people converting classes + # to namespaces. For now we do not warn for this case. + # + # Try matching case 1 first. + match = Match(r'^(.*\)\s*)\{', line) + if match: + # Matched closing parenthesis (case 1). Check the token before the + # matching opening parenthesis, and don't warn if it looks like a + # macro. This avoids these false positives: + # - macro that defines a base class + # - multi-line macro that defines a base class + # - macro that defines the whole class-head + # + # But we still issue warnings for macros that we know are safe to + # warn, specifically: + # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P + # - TYPED_TEST + # - INTERFACE_DEF + # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: + # + # We implement a whitelist of safe macros instead of a blacklist of + # unsafe macros, even though the latter appears less frequently in + # google code and would have been easier to implement. This is because + # the downside for getting the whitelist wrong means some extra + # semicolons, while the downside for getting the blacklist wrong + # would result in compile errors. + # + # In addition to macros, we also don't want to warn on + # - Compound literals + # - Lambdas + # - alignas specifier with anonymous structs: + closing_brace_pos = match.group(1).rfind(')') + opening_parenthesis = ReverseCloseExpression( + clean_lines, linenum, closing_brace_pos) + if opening_parenthesis[2] > -1: + line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] + macro = Search(r'\b([A-Z_]+)\s*$', line_prefix) + func = Match(r'^(.*\])\s*$', line_prefix) + if ((macro and + macro.group(1) not in ( + 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', + 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', + 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or + (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or + Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or + Search(r'\s+=\s*$', line_prefix)): + match = None + if (match and + opening_parenthesis[1] > 1 and + Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])): + # Multi-line lambda-expression + match = None + + else: + # Try matching cases 2-3. + match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) + if not match: + # Try matching cases 4-6. These are always matched on separate lines. + # + # Note that we can't simply concatenate the previous line to the + # current line and do a single match, otherwise we may output + # duplicate warnings for the blank line case: + # if (cond) { + # // blank line + # } + prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] + if prevline and Search(r'[;{}]\s*$', prevline): + match = Match(r'^(\s*)\{', line) + + # Check matching closing brace + #if match: + # (endline, endlinenum, endpos) = CloseExpression( + # clean_lines, linenum, len(match.group(1))) + # if endpos > -1 and Match(r'^\s*;', endline[endpos:]): + # Current {} pair is eligible for semicolon check, and we have found + # the redundant semicolon, output warning here. + # + # Note: because we are scanning forward for opening braces, and + # outputting warnings for the matching closing brace, if there are + # nested blocks with trailing semicolons, we will get the error + # messages in reversed order. + # error(filename, endlinenum, 'readability/braces', 4, + # "You don't need a ; after a }") + + +def CheckEmptyBlockBody(filename, clean_lines, linenum, error): + """Look for empty loop/conditional body with only a single semicolon. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + + # Search for loop keywords at the beginning of the line. Because only + # whitespaces are allowed before the keywords, this will also ignore most + # do-while-loops, since those lines should start with closing brace. + # + # We also check "if" blocks here, since an empty conditional block + # is likely an error. + line = clean_lines.elided[linenum] + matched = Match(r'\s*(for|while|if)\s*\(', line) + if matched: + # Find the end of the conditional expression + (end_line, end_linenum, end_pos) = CloseExpression( + clean_lines, linenum, line.find('(')) + + # Output warning if what follows the condition expression is a semicolon. + # No warning for all other cases, including whitespace or newline, since we + # have a separate check for semicolons preceded by whitespace. + if end_pos >= 0 and Match(r';', end_line[end_pos:]): + if matched.group(1) == 'if': + error(filename, end_linenum, 'whitespace/empty_conditional_body', 5, + 'Empty conditional bodies should use {}') + else: + error(filename, end_linenum, 'whitespace/empty_loop_body', 5, + 'Empty loop bodies should use {} or continue') + + +def FindCheckMacro(line): + """Find a replaceable CHECK-like macro. + + Args: + line: line to search on. + Returns: + (macro name, start position), or (None, -1) if no replaceable + macro is found. + """ + for macro in _CHECK_MACROS: + i = line.find(macro) + if i >= 0: + # Find opening parenthesis. Do a regular expression match here + # to make sure that we are matching the expected CHECK macro, as + # opposed to some other macro that happens to contain the CHECK + # substring. + matched = Match(r'^(.*\b' + macro + r'\s*)\(', line) + if not matched: + continue + return (macro, len(matched.group(1))) + return (None, -1) + + +def CheckCheck(filename, clean_lines, linenum, error): + """Checks the use of CHECK and EXPECT macros. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + + # Decide the set of replacement macros that should be suggested + lines = clean_lines.elided + (check_macro, start_pos) = FindCheckMacro(lines[linenum]) + if not check_macro: + return + + # Find end of the boolean expression by matching parentheses + (last_line, end_line, end_pos) = CloseExpression( + clean_lines, linenum, start_pos) + if end_pos < 0: + return + + # If the check macro is followed by something other than a + # semicolon, assume users will log their own custom error messages + # and don't suggest any replacements. + if not Match(r'\s*;', last_line[end_pos:]): + return + + if linenum == end_line: + expression = lines[linenum][start_pos + 1:end_pos - 1] + else: + expression = lines[linenum][start_pos + 1:] + for i in xrange(linenum + 1, end_line): + expression += lines[i] + expression += last_line[0:end_pos - 1] + + # Parse expression so that we can take parentheses into account. + # This avoids false positives for inputs like "CHECK((a < 4) == b)", + # which is not replaceable by CHECK_LE. + lhs = '' + rhs = '' + operator = None + while expression: + matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' + r'==|!=|>=|>|<=|<|\()(.*)$', expression) + if matched: + token = matched.group(1) + if token == '(': + # Parenthesized operand + expression = matched.group(2) + (end, _) = FindEndOfExpressionInLine(expression, 0, ['(']) + if end < 0: + return # Unmatched parenthesis + lhs += '(' + expression[0:end] + expression = expression[end:] + elif token in ('&&', '||'): + # Logical and/or operators. This means the expression + # contains more than one term, for example: + # CHECK(42 < a && a < b); + # + # These are not replaceable with CHECK_LE, so bail out early. + return + elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): + # Non-relational operator + lhs += token + expression = matched.group(2) + else: + # Relational operator + operator = token + rhs = matched.group(2) + break + else: + # Unparenthesized operand. Instead of appending to lhs one character + # at a time, we do another regular expression match to consume several + # characters at once if possible. Trivial benchmark shows that this + # is more efficient when the operands are longer than a single + # character, which is generally the case. + matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) + if not matched: + matched = Match(r'^(\s*\S)(.*)$', expression) + if not matched: + break + lhs += matched.group(1) + expression = matched.group(2) + + # Only apply checks if we got all parts of the boolean expression + if not (lhs and operator and rhs): + return + + # Check that rhs do not contain logical operators. We already know + # that lhs is fine since the loop above parses out && and ||. + if rhs.find('&&') > -1 or rhs.find('||') > -1: + return + + # At least one of the operands must be a constant literal. This is + # to avoid suggesting replacements for unprintable things like + # CHECK(variable != iterator) + # + # The following pattern matches decimal, hex integers, strings, and + # characters (in that order). + lhs = lhs.strip() + rhs = rhs.strip() + match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' + if Match(match_constant, lhs) or Match(match_constant, rhs): + # Note: since we know both lhs and rhs, we can provide a more + # descriptive error message like: + # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) + # Instead of: + # Consider using CHECK_EQ instead of CHECK(a == b) + # + # We are still keeping the less descriptive message because if lhs + # or rhs gets long, the error message might become unreadable. + error(filename, linenum, 'readability/check', 2, + 'Consider using %s instead of %s(a %s b)' % ( + _CHECK_REPLACEMENT[check_macro][operator], + check_macro, operator)) + + +def CheckAltTokens(filename, clean_lines, linenum, error): + """Check alternative keywords being used in boolean expressions. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Avoid preprocessor lines + if Match(r'^\s*#', line): + return + + # Last ditch effort to avoid multi-line comments. This will not help + # if the comment started before the current line or ended after the + # current line, but it catches most of the false positives. At least, + # it provides a way to workaround this warning for people who use + # multi-line comments in preprocessor macros. + # + # TODO(unknown): remove this once cpplint has better support for + # multi-line comments. + if line.find('/*') >= 0 or line.find('*/') >= 0: + return + + for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): + error(filename, linenum, 'readability/alt_tokens', 2, + 'Use operator %s instead of %s' % ( + _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) + + +def GetLineWidth(line): + """Determines the width of the line in column positions. + + Args: + line: A string, which may be a Unicode string. + + Returns: + The width of the line in column positions, accounting for Unicode + combining characters and wide characters. + """ + if isinstance(line, unicode): + width = 0 + for uc in unicodedata.normalize('NFC', line): + if unicodedata.east_asian_width(uc) in ('W', 'F'): + width += 2 + elif not unicodedata.combining(uc): + width += 1 + return width + else: + return len(line) + + +def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, + error): + """Checks rules from the 'C++ style rules' section of cppguide.html. + + Most of these rules are hard to test (naming, comment style), but we + do what we can. In particular we check for 2-space indents, line lengths, + tab usage, spaces inside code, etc. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + file_extension: The extension (without the dot) of the filename. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + + # Don't use "elided" lines here, otherwise we can't check commented lines. + # Don't want to use "raw" either, because we don't want to check inside C++11 + # raw strings, + raw_lines = clean_lines.lines_without_raw_strings + line = raw_lines[linenum] + + if line.find('\t') != -1: + error(filename, linenum, 'whitespace/tab', 1, + 'Tab found; better to use spaces') + + # One or three blank spaces at the beginning of the line is weird; it's + # hard to reconcile that with 2-space indents. + # NOTE: here are the conditions rob pike used for his tests. Mine aren't + # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces + # if(RLENGTH > 20) complain = 0; + # if(match($0, " +(error|private|public|protected):")) complain = 0; + # if(match(prev, "&& *$")) complain = 0; + # if(match(prev, "\\|\\| *$")) complain = 0; + # if(match(prev, "[\",=><] *$")) complain = 0; + # if(match($0, " <<")) complain = 0; + # if(match(prev, " +for \\(")) complain = 0; + # if(prevodd && match(prevprev, " +for \\(")) complain = 0; + scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$' + classinfo = nesting_state.InnermostClass() + initial_spaces = 0 + cleansed_line = clean_lines.elided[linenum] + while initial_spaces < len(line) and line[initial_spaces] == ' ': + initial_spaces += 1 + if line and line[-1].isspace(): + error(filename, linenum, 'whitespace/end_of_line', 4, + '[LNE_R_TWS]Line ends in whitespace. Consider deleting these extra spaces.') + # There are certain situations we allow one space, notably for + # section labels, and also lines containing multi-line raw strings. + elif ((initial_spaces == 1 or initial_spaces == 3) and + not Match(scope_or_label_pattern, cleansed_line) and + not (clean_lines.raw_lines[linenum] != line and + Match(r'^\s*""', line))): + error(filename, linenum, 'whitespace/indent', 3, + 'Weird number of spaces at line-start. ' + 'Are you using a 2-space indent?') + + # Check if the line is a header guard. + is_header_guard = False + if file_extension == 'h': + cppvar = GetHeaderGuardCPPVariable(filename) + if (line.startswith('#ifndef %s' % cppvar) or + line.startswith('#define %s' % cppvar) or + line.startswith('#endif // %s' % cppvar)): + is_header_guard = True + # #include lines and header guards can be long, since there's no clean way to + # split them. + # + # URLs can be long too. It's possible to split these, but it makes them + # harder to cut&paste. + # + # The "$Id:...$" comment may also get very long without it being the + # developers fault. + """ + if (not line.startswith('#include') and not is_header_guard and + not Match(r'^\s*//.*http(s?)://\S*$', line) and + not Match(r'^// \$Id:.*#[0-9]+ \$$', line)): + line_width = GetLineWidth(line) + extended_length = int((_line_length * 1.25)) + if line_width > extended_length: + error(filename, linenum, 'whitespace/line_length', 4, + 'Lines should very rarely be longer than %i characters' % + extended_length) + elif line_width > _line_length: + error(filename, linenum, 'whitespace/line_length', 2, + 'Lines should be <= %i characters long' % _line_length) + """ + #if (cleansed_line.count(';') > 1 and + # # for loops are allowed two ;'s (and may run over two lines). + # cleansed_line.find('for') == -1 and + # (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or + # GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and + # # It's ok to have many commands in a switch case that fits in 1 line + # not ((cleansed_line.find('case ') != -1 or + # cleansed_line.find('default:') != -1) and + # cleansed_line.find('break;') != -1)): + # error(filename, linenum, 'whitespace/newline', 0, + # 'More than one command on the same line') + + # Some more style checks #test danakim + CheckBraces(filename, clean_lines, linenum, error) + #CheckTrailingSemicolon(filename, clean_lines, linenum, error) + #CheckEmptyBlockBody(filename, clean_lines, linenum, error) + #CheckAccess(filename, clean_lines, linenum, nesting_state, error) + CheckSpacing(filename, clean_lines, linenum, nesting_state, error) + CheckOperatorSpacing(filename, clean_lines, linenum, error) + CheckParenthesisSpacing(filename, clean_lines, linenum, error) + CheckCommaSpacing(filename, clean_lines, linenum, error) + CheckBracesSpacing(filename, clean_lines, linenum, error) + CheckSpacingForFunctionCall(filename, clean_lines, linenum, error) + #CheckRValueReference(filename, clean_lines, linenum, nesting_state, error) + #CheckCheck(filename, clean_lines, linenum, error) + #CheckAltTokens(filename, clean_lines, linenum, error) + classinfo = nesting_state.InnermostClass() + if classinfo: + CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) + + +_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') +# Matches the first component of a filename delimited by -s and _s. That is: +# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' +# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' +# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' +# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' +_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') + + +def _DropCommonSuffixes(filename): + """Drops common suffixes like _test.cc or -inl.h from filename. + + For example: + >>> _DropCommonSuffixes('foo/foo-inl.h') + 'foo/foo' + >>> _DropCommonSuffixes('foo/bar/foo.cc') + 'foo/bar/foo' + >>> _DropCommonSuffixes('foo/foo_internal.h') + 'foo/foo' + >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') + 'foo/foo_unusualinternal' + + Args: + filename: The input filename. + + Returns: + The filename with the common suffix removed. + """ + for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', + 'inl.h', 'impl.h', 'internal.h'): + if (filename.endswith(suffix) and len(filename) > len(suffix) and + filename[-len(suffix) - 1] in ('-', '_')): + return filename[:-len(suffix) - 1] + return os.path.splitext(filename)[0] + + +def _IsTestFilename(filename): + """Determines if the given filename has a suffix that identifies it as a test. + + Args: + filename: The input filename. + + Returns: + True if 'filename' looks like a test, False otherwise. + """ + if (filename.endswith('_test.cc') or + filename.endswith('_unittest.cc') or + filename.endswith('_regtest.cc')): + return True + else: + return False + + +def _ClassifyInclude(fileinfo, include, is_system): + """Figures out what kind of header 'include' is. + + Args: + fileinfo: The current file cpplint is running over. A FileInfo instance. + include: The path to a #included file. + is_system: True if the #include used <> rather than "". + + Returns: + One of the _XXX_HEADER constants. + + For example: + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) + _C_SYS_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) + _CPP_SYS_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) + _LIKELY_MY_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), + ... 'bar/foo_other_ext.h', False) + _POSSIBLE_MY_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) + _OTHER_HEADER + """ + # This is a list of all standard c++ header files, except + # those already checked for above. + is_cpp_h = include in _CPP_HEADERS + + if is_system: + if is_cpp_h: + return _CPP_SYS_HEADER + else: + return _C_SYS_HEADER + + # If the target file and the include we're checking share a + # basename when we drop common extensions, and the include + # lives in . , then it's likely to be owned by the target file. + target_dir, target_base = ( + os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) + include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) + if target_base == include_base and ( + include_dir == target_dir or + include_dir == os.path.normpath(target_dir + '/../public')): + return _LIKELY_MY_HEADER + + # If the target and include share some initial basename + # component, it's possible the target is implementing the + # include, so it's allowed to be first, but we'll never + # complain if it's not there. + target_first_component = _RE_FIRST_COMPONENT.match(target_base) + include_first_component = _RE_FIRST_COMPONENT.match(include_base) + if (target_first_component and include_first_component and + target_first_component.group(0) == + include_first_component.group(0)): + return _POSSIBLE_MY_HEADER + + return _OTHER_HEADER + + + +def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): + """Check rules that are applicable to #include lines. + + Strings on #include lines are NOT removed from elided line, to make + certain tasks easier. However, to prevent false positives, checks + applicable to #include lines in CheckLanguage must be put here. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + include_state: An _IncludeState instance in which the headers are inserted. + error: The function to call with any errors found. + """ + fileinfo = FileInfo(filename) + line = clean_lines.lines[linenum] + + # "include" should use the new style "foo/bar.h" instead of just "bar.h" + # Only do this check if the included header follows google naming + # conventions. If not, assume that it's a 3rd party API that + # requires special include conventions. + # + # We also make an exception for Lua headers, which follow google + # naming convention but not the include convention. + match = Match(r'#include\s*"([^/]+\.h)"', line) + if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)): + error(filename, linenum, 'build/include', 4, + 'Include the directory when naming .h files') + + # we shouldn't include a file more than once. actually, there are a + # handful of instances where doing so is okay, but in general it's + # not. + match = _RE_PATTERN_INCLUDE.search(line) + if match: + include = match.group(2) + is_system = (match.group(1) == '<') + duplicate_line = include_state.FindHeader(include) + if duplicate_line >= 0: + error(filename, linenum, 'build/include', 4, + '"%s" already included at %s:%s' % + (include, filename, duplicate_line)) + elif (include.endswith('.cc') and + os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)): + error(filename, linenum, 'build/include', 4, + 'Do not include .cc files from other packages') + elif not _THIRD_PARTY_HEADERS_PATTERN.match(include): + include_state.include_list[-1].append((include, linenum)) + + # We want to ensure that headers appear in the right order: + # 1) for foo.cc, foo.h (preferred location) + # 2) c system files + # 3) cpp system files + # 4) for foo.cc, foo.h (deprecated location) + # 5) other google headers + # + # We classify each include statement as one of those 5 types + # using a number of techniques. The include_state object keeps + # track of the highest type seen, and complains if we see a + # lower type after that. + error_message = include_state.CheckNextIncludeOrder( + _ClassifyInclude(fileinfo, include, is_system)) + if error_message: + error(filename, linenum, 'build/include_order', 4, + '%s. Should be: %s.h, c system, c++ system, other.' % + (error_message, fileinfo.BaseName())) + canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) + if not include_state.IsInAlphabeticalOrder( + clean_lines, linenum, canonical_include): + error(filename, linenum, 'build/include_alpha', 4, + 'Include "%s" not in alphabetical order' % include) + include_state.SetLastHeader(canonical_include) + + + +def _GetTextInside(text, start_pattern): + r"""Retrieves all the text between matching open and close parentheses. + + Given a string of lines and a regular expression string, retrieve all the text + following the expression and between opening punctuation symbols like + (, [, or {, and the matching close-punctuation symbol. This properly nested + occurrences of the punctuations, so for the text like + printf(a(), b(c())); + a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. + start_pattern must match string having an open punctuation symbol at the end. + + Args: + text: The lines to extract text. Its comments and strings must be elided. + It can be single line and can span multiple lines. + start_pattern: The regexp string indicating where to start extracting + the text. + Returns: + The extracted text. + None if either the opening string or ending punctuation could not be found. + """ + # TODO(unknown): Audit cpplint.py to see what places could be profitably + # rewritten to use _GetTextInside (and use inferior regexp matching today). + + # Give opening punctuations to get the matching close-punctuations. + matching_punctuation = {'(': ')', '{': '}', '[': ']'} + closing_punctuation = set(matching_punctuation.itervalues()) + + # Find the position to start extracting text. + match = re.search(start_pattern, text, re.M) + if not match: # start_pattern not found in text. + return None + start_position = match.end(0) + + assert start_position > 0, ( + 'start_pattern must ends with an opening punctuation.') + assert text[start_position - 1] in matching_punctuation, ( + 'start_pattern must ends with an opening punctuation.') + # Stack of closing punctuations we expect to have in text after position. + punctuation_stack = [matching_punctuation[text[start_position - 1]]] + position = start_position + while punctuation_stack and position < len(text): + if text[position] == punctuation_stack[-1]: + punctuation_stack.pop() + elif text[position] in closing_punctuation: + # A closing punctuation without matching opening punctuations. + return None + elif text[position] in matching_punctuation: + punctuation_stack.append(matching_punctuation[text[position]]) + position += 1 + if punctuation_stack: + # Opening punctuations left without matching close-punctuations. + return None + # punctuations match. + return text[start_position:position - 1] + + +# Patterns for matching call-by-reference parameters. +# +# Supports nested templates up to 2 levels deep using this messy pattern: +# < (?: < (?: < [^<>]* +# > +# | [^<>] )* +# > +# | [^<>] )* +# > +_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]* +_RE_PATTERN_TYPE = ( + r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?' + r'(?:\w|' + r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|' + r'::)+') +# A call-by-reference parameter ends with '& identifier'. +_RE_PATTERN_REF_PARAM = re.compile( + r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*' + r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]') +# A call-by-const-reference parameter either ends with 'const& identifier' +# or looks like 'const type& identifier' when 'type' is atomic. +_RE_PATTERN_CONST_REF_PARAM = ( + r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT + + r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')') + + +def CheckLanguage(filename, clean_lines, linenum, file_extension, + include_state, nesting_state, error): + """Checks rules from the 'C++ language rules' section of cppguide.html. + + Some of these rules are hard to test (function overloading, using + uint32 inappropriately), but we do the best we can. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + file_extension: The extension (without the dot) of the filename. + include_state: An _IncludeState instance in which the headers are inserted. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + # If the line is empty or consists of entirely a comment, no need to + # check it. + line = clean_lines.elided[linenum] + if not line: + return + + match = _RE_PATTERN_INCLUDE.search(line) + if match: + CheckIncludeLine(filename, clean_lines, linenum, include_state, error) + return + + # Reset include state across preprocessor directives. This is meant + # to silence warnings for conditional includes. + match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line) + if match: + include_state.ResetSection(match.group(1)) + + # Make Windows paths like Unix. + fullname = os.path.abspath(filename).replace('\\', '/') + + # Perform other checks now that we are sure that this is not an include line + CheckCasts(filename, clean_lines, linenum, error) + CheckGlobalStatic(filename, clean_lines, linenum, error) + CheckPrintf(filename, clean_lines, linenum, error) + + if file_extension == 'h': + # TODO(unknown): check that 1-arg constructors are explicit. + # How to tell it's a constructor? + # (handled in CheckForNonStandardConstructs for now) + # TODO(unknown): check that classes declare or disable copy/assign + # (level 1 error) + pass + + # Check if people are using the verboten C basic types. The only exception + # we regularly allow is "unsigned short port" for port. + if Search(r'\bshort port\b', line): + if not Search(r'\bunsigned short port\b', line): + error(filename, linenum, 'runtime/int', 4, + 'Use "unsigned short" for ports, not "short"') + else: + match = Search(r'\b(short|long(?! +double)|long long)\b', line) + if match: + error(filename, linenum, 'runtime/int', 4, + 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) + + # Check if some verboten operator overloading is going on + # TODO(unknown): catch out-of-line unary operator&: + # class X {}; + # int operator&(const X& x) { return 42; } // unary operator& + # The trick is it's hard to tell apart from binary operator&: + # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& + if Search(r'\boperator\s*&\s*\(\s*\)', line): + error(filename, linenum, 'runtime/operator', 4, + 'Unary operator& is dangerous. Do not use it.') + + # Check for suspicious usage of "if" like + # } if (a == b) { + if Search(r'\}\s*if\s*\(', line): + error(filename, linenum, 'readability/braces', 4, + '[BRC_M_SMT]Did you mean "else if"? If not, start a new line for "if".') + + # Check for potential format string bugs like printf(foo). + # We constrain the pattern not to pick things like DocidForPrintf(foo). + # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) + # TODO(unknown): Catch the following case. Need to change the calling + # convention of the whole function to process multiple line to handle it. + # printf( + # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); + printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') + if printf_args: + match = Match(r'([\w.\->()]+)$', printf_args) + if match and match.group(1) != '__VA_ARGS__': + function_name = re.search(r'\b((?:string)?printf)\s*\(', + line, re.I).group(1) + error(filename, linenum, 'runtime/printf', 4, + 'Potential format string bug. Do %s("%%s", %s) instead.' + % (function_name, match.group(1))) + + # Check for potential memset bugs like memset(buf, sizeof(buf), 0). + match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) + if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): + error(filename, linenum, 'runtime/memset', 4, + 'Did you mean "memset(%s, 0, %s)"?' + % (match.group(1), match.group(2))) + + if Search(r'\busing namespace\b', line): + error(filename, linenum, 'build/namespaces', 5, + 'Do not use namespace using-directives. ' + 'Use using-declarations instead.') + + # Detect variable-length arrays. + match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) + if (match and match.group(2) != 'return' and match.group(2) != 'delete' and + match.group(3).find(']') == -1): + # Split the size using space and arithmetic operators as delimiters. + # If any of the resulting tokens are not compile time constants then + # report the error. + tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) + is_const = True + skip_next = False + for tok in tokens: + if skip_next: + skip_next = False + continue + + if Search(r'sizeof\(.+\)', tok): continue + if Search(r'arraysize\(\w+\)', tok): continue + + tok = tok.lstrip('(') + tok = tok.rstrip(')') + if not tok: continue + if Match(r'\d+', tok): continue + if Match(r'0[xX][0-9a-fA-F]+', tok): continue + if Match(r'k[A-Z0-9]\w*', tok): continue + if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue + if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue + # A catch all for tricky sizeof cases, including 'sizeof expression', + # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' + # requires skipping the next token because we split on ' ' and '*'. + if tok.startswith('sizeof'): + skip_next = True + continue + is_const = False + break + if not is_const: + error(filename, linenum, 'runtime/arrays', 1, + 'Do not use variable-length arrays. Use an appropriately named ' + "('k' followed by CamelCase) compile-time constant for the size.") + + # Check for use of unnamed namespaces in header files. Registration + # macros are typically OK, so we allow use of "namespace {" on lines + # that end with backslashes. + if (file_extension == 'h' + and Search(r'\bnamespace\s*{', line) + and line[-1] != '\\'): + error(filename, linenum, 'build/namespaces', 4, + 'Do not use unnamed namespaces in header files. See ' + 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' + ' for more information.') + + +def CheckGlobalStatic(filename, clean_lines, linenum, error): + """Check for unsafe global or static objects. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Match two lines at a time to support multiline declarations + if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line): + line += clean_lines.elided[linenum + 1].strip() + + # Check for people declaring static/global STL strings at the top level. + # This is dangerous because the C++ language does not guarantee that + # globals with constructors are initialized before the first access. + match = Match( + r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)', + line) + + # Remove false positives: + # - String pointers (as opposed to values). + # string *pointer + # const string *pointer + # string const *pointer + # string *const pointer + # + # - Functions and template specializations. + # string Function(... + # string Class::Method(... + # + # - Operators. These are matched separately because operator names + # cross non-word boundaries, and trying to match both operators + # and functions at the same time would decrease accuracy of + # matching identifiers. + # string Class::operator*() + if (match and + not Search(r'\bstring\b(\s+const)?\s*\*\s*(const\s+)?\w', line) and + not Search(r'\boperator\W', line) and + not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(3))): + error(filename, linenum, 'runtime/string', 4, + 'For a static/global string constant, use a C style string instead: ' + '"%schar %s[]".' % + (match.group(1), match.group(2))) + + if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line): + error(filename, linenum, 'runtime/init', 4, + 'You seem to be initializing a member variable with itself.') + + +def CheckPrintf(filename, clean_lines, linenum, error): + """Check for printf related issues. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # When snprintf is used, the second argument shouldn't be a literal. + match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) + if match and match.group(2) != '0': + # If 2nd arg is zero, snprintf is used to calculate size. + error(filename, linenum, 'runtime/printf', 3, + 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' + 'to snprintf.' % (match.group(1), match.group(2))) + + # Check if some verboten C functions are being used. + if Search(r'\bsprintf\s*\(', line): + error(filename, linenum, 'runtime/printf', 5, + 'Never use sprintf. Use snprintf instead.') + match = Search(r'\b(strcpy|strcat)\s*\(', line) + if match: + error(filename, linenum, 'runtime/printf', 4, + 'Almost always, snprintf is better than %s' % match.group(1)) + + +def IsDerivedFunction(clean_lines, linenum): + """Check if current line contains an inherited function. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + Returns: + True if current line contains a function with "override" + virt-specifier. + """ + # Scan back a few lines for start of current function + for i in xrange(linenum, max(-1, linenum - 10), -1): + match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i]) + if match: + # Look for "override" after the matching closing parenthesis + line, _, closing_paren = CloseExpression( + clean_lines, i, len(match.group(1))) + return (closing_paren >= 0 and + Search(r'\boverride\b', line[closing_paren:])) + return False + + +def IsOutOfLineMethodDefinition(clean_lines, linenum): + """Check if current line contains an out-of-line method definition. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + Returns: + True if current line contains an out-of-line method definition. + """ + # Scan back a few lines for start of current function + for i in xrange(linenum, max(-1, linenum - 10), -1): + if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]): + return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None + return False + + +def IsInitializerList(clean_lines, linenum): + """Check if current line is inside constructor initializer list. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + Returns: + True if current line appears to be inside constructor initializer + list, False otherwise. + """ + for i in xrange(linenum, 1, -1): + line = clean_lines.elided[i] + if i == linenum: + remove_function_body = Match(r'^(.*)\{\s*$', line) + if remove_function_body: + line = remove_function_body.group(1) + + if Search(r'\s:\s*\w+[({]', line): + # A lone colon tend to indicate the start of a constructor + # initializer list. It could also be a ternary operator, which + # also tend to appear in constructor initializer lists as + # opposed to parameter lists. + return True + if Search(r'\}\s*,\s*$', line): + # A closing brace followed by a comma is probably the end of a + # brace-initialized member in constructor initializer list. + return True + if Search(r'[{};]\s*$', line): + # Found one of the following: + # - A closing brace or semicolon, probably the end of the previous + # function. + # - An opening brace, probably the start of current class or namespace. + # + # Current line is probably not inside an initializer list since + # we saw one of those things without seeing the starting colon. + return False + + # Got to the beginning of the file without seeing the start of + # constructor initializer list. + return False + + +def CheckForNonConstReference(filename, clean_lines, linenum, + nesting_state, error): + """Check for non-const references. + + Separate from CheckLanguage since it scans backwards from current + line, instead of scanning forward. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + # Do nothing if there is no '&' on current line. + line = clean_lines.elided[linenum] + if '&' not in line: + return + + # If a function is inherited, current function doesn't have much of + # a choice, so any non-const references should not be blamed on + # derived function. + if IsDerivedFunction(clean_lines, linenum): + return + + # Don't warn on out-of-line method definitions, as we would warn on the + # in-line declaration, if it isn't marked with 'override'. + if IsOutOfLineMethodDefinition(clean_lines, linenum): + return + + # Long type names may be broken across multiple lines, usually in one + # of these forms: + # LongType + # ::LongTypeContinued &identifier + # LongType:: + # LongTypeContinued &identifier + # LongType< + # ...>::LongTypeContinued &identifier + # + # If we detected a type split across two lines, join the previous + # line to current line so that we can match const references + # accordingly. + # + # Note that this only scans back one line, since scanning back + # arbitrary number of lines would be expensive. If you have a type + # that spans more than 2 lines, please use a typedef. + if linenum > 1: + previous = None + if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): + # previous_line\n + ::current_line + previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', + clean_lines.elided[linenum - 1]) + elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): + # previous_line::\n + current_line + previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', + clean_lines.elided[linenum - 1]) + if previous: + line = previous.group(1) + line.lstrip() + else: + # Check for templated parameter that is split across multiple lines + endpos = line.rfind('>') + if endpos > -1: + (_, startline, startpos) = ReverseCloseExpression( + clean_lines, linenum, endpos) + if startpos > -1 and startline < linenum: + # Found the matching < on an earlier line, collect all + # pieces up to current line. + line = '' + for i in xrange(startline, linenum + 1): + line += clean_lines.elided[i].strip() + + # Check for non-const references in function parameters. A single '&' may + # found in the following places: + # inside expression: binary & for bitwise AND + # inside expression: unary & for taking the address of something + # inside declarators: reference parameter + # We will exclude the first two cases by checking that we are not inside a + # function body, including one that was just introduced by a trailing '{'. + # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. + if (nesting_state.previous_stack_top and + not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or + isinstance(nesting_state.previous_stack_top, _NamespaceInfo))): + # Not at toplevel, not within a class, and not within a namespace + return + + # Avoid initializer lists. We only need to scan back from the + # current line for something that starts with ':'. + # + # We don't need to check the current line, since the '&' would + # appear inside the second set of parentheses on the current line as + # opposed to the first set. + if linenum > 0: + for i in xrange(linenum - 1, max(0, linenum - 10), -1): + previous_line = clean_lines.elided[i] + if not Search(r'[),]\s*$', previous_line): + break + if Match(r'^\s*:\s+\S', previous_line): + return + + # Avoid preprocessors + if Search(r'\\\s*$', line): + return + + # Avoid constructor initializer lists + if IsInitializerList(clean_lines, linenum): + return + + # We allow non-const references in a few standard places, like functions + # called "swap()" or iostream operators like "<<" or ">>". Do not check + # those function parameters. + # + # We also accept & in static_assert, which looks like a function but + # it's actually a declaration expression. + whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|' + r'operator\s*[<>][<>]|' + r'static_assert|COMPILE_ASSERT' + r')\s*\(') + if Search(whitelisted_functions, line): + return + elif not Search(r'\S+\([^)]*$', line): + # Don't see a whitelisted function on this line. Actually we + # didn't see any function name on this line, so this is likely a + # multi-line parameter list. Try a bit harder to catch this case. + for i in xrange(2): + if (linenum > i and + Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])): + return + + decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body + for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): + if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter): + error(filename, linenum, 'runtime/references', 2, + 'Is this a non-const reference? ' + 'If so, make const or use a pointer: ' + + ReplaceAll(' *<', '<', parameter)) + + +def CheckCasts(filename, clean_lines, linenum, error): + """Various cast related checks. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Check to see if they're using an conversion function cast. + # I just try to capture the most common basic types, though there are more. + # Parameterless conversion functions, such as bool(), are allowed as they are + # probably a member operator declaration or default constructor. + match = Search( + r'(\bnew\s+|\S<\s*(?:const\s+)?)?\b' + r'(int|float|double|bool|char|int32|uint32|int64|uint64)' + r'(\([^)].*)', line) + expecting_function = ExpectingFunctionArgs(clean_lines, linenum) + if match and not expecting_function: + matched_type = match.group(2) + + # matched_new_or_template is used to silence two false positives: + # - New operators + # - Template arguments with function types + # + # For template arguments, we match on types immediately following + # an opening bracket without any spaces. This is a fast way to + # silence the common case where the function type is the first + # template argument. False negative with less-than comparison is + # avoided because those operators are usually followed by a space. + # + # function // bracket + no space = false positive + # value < double(42) // bracket + space = true positive + matched_new_or_template = match.group(1) + + # Avoid arrays by looking for brackets that come after the closing + # parenthesis. + if Match(r'\([^()]+\)\s*\[', match.group(3)): + return + + # Other things to ignore: + # - Function pointers + # - Casts to pointer types + # - Placement new + # - Alias declarations + matched_funcptr = match.group(3) + if (matched_new_or_template is None and + not (matched_funcptr and + (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(', + matched_funcptr) or + matched_funcptr.startswith('(*)'))) and + not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and + not Search(r'new\(\S+\)\s*' + matched_type, line)): + error(filename, linenum, 'readability/casting', 4, + 'Using deprecated casting style. ' + 'Use static_cast<%s>(...) instead' % + matched_type) + + if not expecting_function: + CheckCStyleCast(filename, clean_lines, linenum, 'static_cast', + r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) + + # This doesn't catch all cases. Consider (const char * const)"hello". + # + # (char *) "foo" should always be a const_cast (reinterpret_cast won't + # compile). + if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast', + r'\((char\s?\*+\s?)\)\s*"', error): + pass + else: + # Check pointer casts for other than string constants + CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast', + r'\((\w+\s?\*+\s?)\)', error) + + # In addition, we look for people taking the address of a cast. This + # is dangerous -- casts can assign to temporaries, so the pointer doesn't + # point where you think. + # + # Some non-identifier character is required before the '&' for the + # expression to be recognized as a cast. These are casts: + # expression = &static_cast(temporary()); + # function(&(int*)(temporary())); + # + # This is not a cast: + # reference_type&(int* function_param); + match = Search( + r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|' + r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line) + if match: + # Try a better error message when the & is bound to something + # dereferenced by the casted pointer, as opposed to the casted + # pointer itself. + parenthesis_error = False + match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line) + if match: + _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1))) + if x1 >= 0 and clean_lines.elided[y1][x1] == '(': + _, y2, x2 = CloseExpression(clean_lines, y1, x1) + if x2 >= 0: + extended_line = clean_lines.elided[y2][x2:] + if y2 < clean_lines.NumLines() - 1: + extended_line += clean_lines.elided[y2 + 1] + if Match(r'\s*(?:->|\[)', extended_line): + parenthesis_error = True + + if parenthesis_error: + error(filename, linenum, 'readability/casting', 4, + ('Are you taking an address of something dereferenced ' + 'from a cast? Wrapping the dereferenced expression in ' + 'parentheses will make the binding more obvious')) + else: + error(filename, linenum, 'runtime/casting', 4, + ('Are you taking an address of a cast? ' + 'This is dangerous: could be a temp var. ' + 'Take the address before doing the cast, rather than after')) + + +def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): + """Checks for a C-style cast by looking for the pattern. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + cast_type: The string for the C++ cast to recommend. This is either + reinterpret_cast, static_cast, or const_cast, depending. + pattern: The regular expression used to find C-style casts. + error: The function to call with any errors found. + + Returns: + True if an error was emitted. + False otherwise. + """ + line = clean_lines.elided[linenum] + match = Search(pattern, line) + if not match: + return False + + # Exclude lines with keywords that tend to look like casts + context = line[0:match.start(1) - 1] + if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): + return False + + # Try expanding current context to see if we one level of + # parentheses inside a macro. + if linenum > 0: + for i in xrange(linenum - 1, max(0, linenum - 5), -1): + context = clean_lines.elided[i] + context + if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): + return False + + # operator++(int) and operator--(int) + if context.endswith(' operator++') or context.endswith(' operator--'): + return False + + # A single unnamed argument for a function tends to look like old + # style cast. If we see those, don't issue warnings for deprecated + # casts, instead issue warnings for unnamed arguments where + # appropriate. + # + # These are things that we want warnings for, since the style guide + # explicitly require all parameters to be named: + # Function(int); + # Function(int) { + # ConstMember(int) const; + # ConstMember(int) const { + # ExceptionMember(int) throw (...); + # ExceptionMember(int) throw (...) { + # PureVirtual(int) = 0; + # [](int) -> bool { + # + # These are functions of some sort, where the compiler would be fine + # if they had named parameters, but people often omit those + # identifiers to reduce clutter: + # (FunctionPointer)(int); + # (FunctionPointer)(int) = value; + # Function((function_pointer_arg)(int)) + # Function((function_pointer_arg)(int), int param) + # ; + # <(FunctionPointerTemplateArgument)(int)>; + remainder = line[match.end(0):] + if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)', + remainder): + # Looks like an unnamed parameter. + + # Don't warn on any kind of template arguments. + if Match(r'^\s*>', remainder): + return False + + # Don't warn on assignments to function pointers, but keep warnings for + # unnamed parameters to pure virtual functions. Note that this pattern + # will also pass on assignments of "0" to function pointers, but the + # preferred values for those would be "nullptr" or "NULL". + matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder) + if matched_zero and matched_zero.group(1) != '0': + return False + + # Don't warn on function pointer declarations. For this we need + # to check what came before the "(type)" string. + if Match(r'.*\)\s*$', line[0:match.start(0)]): + return False + + # Don't warn if the parameter is named with block comments, e.g.: + # Function(int /*unused_param*/); + raw_line = clean_lines.raw_lines[linenum] + if '/*' in raw_line: + return False + + # Passed all filters, issue warning here. + error(filename, linenum, 'readability/function', 3, + 'All parameters should be named in a function') + return True + + # At this point, all that should be left is actual casts. + error(filename, linenum, 'readability/casting', 4, + 'Using C-style cast. Use %s<%s>(...) instead' % + (cast_type, match.group(1))) + + return True + + +def ExpectingFunctionArgs(clean_lines, linenum): + """Checks whether where function type arguments are expected. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + + Returns: + True if the line at 'linenum' is inside something that expects arguments + of function types. + """ + line = clean_lines.elided[linenum] + return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or + (linenum >= 2 and + (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', + clean_lines.elided[linenum - 1]) or + Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', + clean_lines.elided[linenum - 2]) or + Search(r'\bstd::m?function\s*\<\s*$', + clean_lines.elided[linenum - 1])))) + + +_HEADERS_CONTAINING_TEMPLATES = ( + ('', ('deque',)), + ('', ('unary_function', 'binary_function', + 'plus', 'minus', 'multiplies', 'divides', 'modulus', + 'negate', + 'equal_to', 'not_equal_to', 'greater', 'less', + 'greater_equal', 'less_equal', + 'logical_and', 'logical_or', 'logical_not', + 'unary_negate', 'not1', 'binary_negate', 'not2', + 'bind1st', 'bind2nd', + 'pointer_to_unary_function', + 'pointer_to_binary_function', + 'ptr_fun', + 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t', + 'mem_fun_ref_t', + 'const_mem_fun_t', 'const_mem_fun1_t', + 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t', + 'mem_fun_ref', + )), + ('', ('numeric_limits',)), + ('', ('list',)), + ('', ('map', 'multimap',)), + ('', ('allocator',)), + ('', ('queue', 'priority_queue',)), + ('', ('set', 'multiset',)), + ('', ('stack',)), + ('', ('char_traits', 'basic_string',)), + ('', ('tuple',)), + ('', ('pair',)), + ('', ('vector',)), + + # gcc extensions. + # Note: std::hash is their hash, ::hash is our hash + ('', ('hash_map', 'hash_multimap',)), + ('', ('hash_set', 'hash_multiset',)), + ('', ('slist',)), + ) + +_RE_PATTERN_STRING = re.compile(r'\bstring\b') + +_re_pattern_algorithm_header = [] +for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap', + 'transform'): + # Match max(..., ...), max(..., ...), but not foo->max, foo.max or + # type::max(). + _re_pattern_algorithm_header.append( + (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'), + _template, + '')) + +_re_pattern_templates = [] +for _header, _templates in _HEADERS_CONTAINING_TEMPLATES: + for _template in _templates: + _re_pattern_templates.append( + (re.compile(r'(\<|\b)' + _template + r'\s*\<'), + _template + '<>', + _header)) + + +def FilesBelongToSameModule(filename_cc, filename_h): + """Check if these two filenames belong to the same module. + + The concept of a 'module' here is a as follows: + foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the + same 'module' if they are in the same directory. + some/path/public/xyzzy and some/path/internal/xyzzy are also considered + to belong to the same module here. + + If the filename_cc contains a longer path than the filename_h, for example, + '/absolute/path/to/base/sysinfo.cc', and this file would include + 'base/sysinfo.h', this function also produces the prefix needed to open the + header. This is used by the caller of this function to more robustly open the + header file. We don't have access to the real include paths in this context, + so we need this guesswork here. + + Known bugs: tools/base/bar.cc and base/bar.h belong to the same module + according to this implementation. Because of this, this function gives + some false positives. This should be sufficiently rare in practice. + + Args: + filename_cc: is the path for the .cc file + filename_h: is the path for the header path + + Returns: + Tuple with a bool and a string: + bool: True if filename_cc and filename_h belong to the same module. + string: the additional prefix needed to open the header file. + """ + + if not filename_cc.endswith('.cc'): + return (False, '') + filename_cc = filename_cc[:-len('.cc')] + if filename_cc.endswith('_unittest'): + filename_cc = filename_cc[:-len('_unittest')] + elif filename_cc.endswith('_test'): + filename_cc = filename_cc[:-len('_test')] + filename_cc = filename_cc.replace('/public/', '/') + filename_cc = filename_cc.replace('/internal/', '/') + + if not filename_h.endswith('.h'): + return (False, '') + filename_h = filename_h[:-len('.h')] + if filename_h.endswith('-inl'): + filename_h = filename_h[:-len('-inl')] + filename_h = filename_h.replace('/public/', '/') + filename_h = filename_h.replace('/internal/', '/') + + files_belong_to_same_module = filename_cc.endswith(filename_h) + common_path = '' + if files_belong_to_same_module: + common_path = filename_cc[:-len(filename_h)] + return files_belong_to_same_module, common_path + + +def UpdateIncludeState(filename, include_dict, io=codecs): + """Fill up the include_dict with new includes found from the file. + + Args: + filename: the name of the header to read. + include_dict: a dictionary in which the headers are inserted. + io: The io factory to use to read the file. Provided for testability. + + Returns: + True if a header was successfully added. False otherwise. + """ + headerfile = None + try: + headerfile = io.open(filename, 'r', 'utf8', 'replace') + except IOError: + return False + linenum = 0 + for line in headerfile: + linenum += 1 + clean_line = CleanseComments(line) + match = _RE_PATTERN_INCLUDE.search(clean_line) + if match: + include = match.group(2) + include_dict.setdefault(include, linenum) + return True + + +def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, + io=codecs): + """Reports for missing stl includes. + + This function will output warnings to make sure you are including the headers + necessary for the stl containers and functions that you use. We only give one + reason to include a header. For example, if you use both equal_to<> and + less<> in a .h file, only one (the latter in the file) of these will be + reported as a reason to include the . + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + include_state: An _IncludeState instance. + error: The function to call with any errors found. + io: The IO factory to use to read the header file. Provided for unittest + injection. + """ + required = {} # A map of header name to linenumber and the template entity. + # Example of required: { '': (1219, 'less<>') } + + for linenum in xrange(clean_lines.NumLines()): + line = clean_lines.elided[linenum] + if not line or line[0] == '#': + continue + + # String is special -- it is a non-templatized type in STL. + matched = _RE_PATTERN_STRING.search(line) + if matched: + # Don't warn about strings in non-STL namespaces: + # (We check only the first match per line; good enough.) + prefix = line[:matched.start()] + if prefix.endswith('std::') or not prefix.endswith('::'): + required[''] = (linenum, 'string') + + for pattern, template, header in _re_pattern_algorithm_header: + if pattern.search(line): + required[header] = (linenum, template) + + # The following function is just a speed up, no semantics are changed. + if not '<' in line: # Reduces the cpu time usage by skipping lines. + continue + + for pattern, template, header in _re_pattern_templates: + if pattern.search(line): + required[header] = (linenum, template) + + # The policy is that if you #include something in foo.h you don't need to + # include it again in foo.cc. Here, we will look at possible includes. + # Let's flatten the include_state include_list and copy it into a dictionary. + include_dict = dict([item for sublist in include_state.include_list + for item in sublist]) + + # Did we find the header for this file (if any) and successfully load it? + header_found = False + + # Use the absolute path so that matching works properly. + abs_filename = FileInfo(filename).FullName() + + # For Emacs's flymake. + # If cpplint is invoked from Emacs's flymake, a temporary file is generated + # by flymake and that file name might end with '_flymake.cc'. In that case, + # restore original file name here so that the corresponding header file can be + # found. + # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' + # instead of 'foo_flymake.h' + abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) + + # include_dict is modified during iteration, so we iterate over a copy of + # the keys. + header_keys = include_dict.keys() + for header in header_keys: + (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) + fullpath = common_path + header + if same_module and UpdateIncludeState(fullpath, include_dict, io): + header_found = True + + # If we can't find the header file for a .cc, assume it's because we don't + # know where to look. In that case we'll give up as we're not sure they + # didn't include it in the .h file. + # TODO(unknown): Do a better job of finding .h files so we are confident that + # not having the .h file means there isn't one. + if filename.endswith('.cc') and not header_found: + return + + # All the lines have been processed, report the errors found. + for required_header_unstripped in required: + template = required[required_header_unstripped][1] + if required_header_unstripped.strip('<>"') not in include_dict: + error(filename, required[required_header_unstripped][0], + 'build/include_what_you_use', 4, + 'Add #include ' + required_header_unstripped + ' for ' + template) + + +_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<') + + +def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): + """Check that make_pair's template arguments are deduced. + + G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are + specified explicitly, and such use isn't intended in any case. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) + if match: + error(filename, linenum, 'build/explicit_make_pair', + 4, # 4 = high confidence + 'For C++11-compatibility, omit template arguments from make_pair' + ' OR use pair directly OR if appropriate, construct a pair directly') + + +def CheckDefaultLambdaCaptures(filename, clean_lines, linenum, error): + """Check that default lambda captures are not used. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # A lambda introducer specifies a default capture if it starts with "[=" + # or if it starts with "[&" _not_ followed by an identifier. + match = Match(r'^(.*)\[\s*(?:=|&[^\w])', line) + if match: + # Found a potential error, check what comes after the lambda-introducer. + # If it's not open parenthesis (for lambda-declarator) or open brace + # (for compound-statement), it's not a lambda. + line, _, pos = CloseExpression(clean_lines, linenum, len(match.group(1))) + if pos >= 0 and Match(r'^\s*[{(]', line[pos:]): + error(filename, linenum, 'build/c++11', + 4, # 4 = high confidence + 'Default lambda captures are an unapproved C++ feature.') + + +def CheckRedundantVirtual(filename, clean_lines, linenum, error): + """Check if line contains a redundant "virtual" function-specifier. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + # Look for "virtual" on current line. + line = clean_lines.elided[linenum] + virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line) + if not virtual: return + + # Ignore "virtual" keywords that are near access-specifiers. These + # are only used in class base-specifier and do not apply to member + # functions. + if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or + Match(r'^\s+(public|protected|private)\b', virtual.group(3))): + return + + # Ignore the "virtual" keyword from virtual base classes. Usually + # there is a column on the same line in these cases (virtual base + # classes are rare in google3 because multiple inheritance is rare). + if Match(r'^.*[^:]:[^:].*$', line): return + + # Look for the next opening parenthesis. This is the start of the + # parameter list (possibly on the next line shortly after virtual). + # TODO(unknown): doesn't work if there are virtual functions with + # decltype() or other things that use parentheses, but csearch suggests + # that this is rare. + end_col = -1 + end_line = -1 + start_col = len(virtual.group(2)) + for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())): + line = clean_lines.elided[start_line][start_col:] + parameter_list = Match(r'^([^(]*)\(', line) + if parameter_list: + # Match parentheses to find the end of the parameter list + (_, end_line, end_col) = CloseExpression( + clean_lines, start_line, start_col + len(parameter_list.group(1))) + break + start_col = 0 + + if end_col < 0: + return # Couldn't find end of parameter list, give up + + # Look for "override" or "final" after the parameter list + # (possibly on the next few lines). + for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())): + line = clean_lines.elided[i][end_col:] + match = Search(r'\b(override|final)\b', line) + if match: + error(filename, linenum, 'readability/inheritance', 4, + ('"virtual" is redundant since function is ' + 'already declared as "%s"' % match.group(1))) + + # Set end_col to check whole lines after we are done with the + # first line. + end_col = 0 + if Search(r'[^\w]\s*$', line): + break + + +def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error): + """Check if line contains a redundant "override" or "final" virt-specifier. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + # Look for closing parenthesis nearby. We need one to confirm where + # the declarator ends and where the virt-specifier starts to avoid + # false positives. + line = clean_lines.elided[linenum] + declarator_end = line.rfind(')') + if declarator_end >= 0: + fragment = line[declarator_end:] + else: + if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0: + fragment = line + else: + return + + # Check that at most one of "override" or "final" is present, not both + if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment): + error(filename, linenum, 'readability/inheritance', 4, + ('"override" is redundant since function is ' + 'already declared as "final"')) + + + + +# Returns true if we are at a new block, and it is directly +# inside of a namespace. +def IsBlockInNameSpace(nesting_state, is_forward_declaration): + """Checks that the new block is directly in a namespace. + + Args: + nesting_state: The _NestingState object that contains info about our state. + is_forward_declaration: If the class is a forward declared class. + Returns: + Whether or not the new block is directly in a namespace. + """ + if is_forward_declaration: + if len(nesting_state.stack) >= 1 and ( + isinstance(nesting_state.stack[-1], _NamespaceInfo)): + return True + else: + return False + + return (len(nesting_state.stack) > 1 and + nesting_state.stack[-1].check_namespace_indentation and + isinstance(nesting_state.stack[-2], _NamespaceInfo)) + + +def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, + raw_lines_no_comments, linenum): + """This method determines if we should apply our namespace indentation check. + + Args: + nesting_state: The current nesting state. + is_namespace_indent_item: If we just put a new class on the stack, True. + If the top of the stack is not a class, or we did not recently + add the class, False. + raw_lines_no_comments: The lines without the comments. + linenum: The current line number we are processing. + + Returns: + True if we should apply our namespace indentation check. Currently, it + only works for classes and namespaces inside of a namespace. + """ + + is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments, + linenum) + + if not (is_namespace_indent_item or is_forward_declaration): + return False + + # If we are in a macro, we do not want to check the namespace indentation. + if IsMacroDefinition(raw_lines_no_comments, linenum): + return False + + return IsBlockInNameSpace(nesting_state, is_forward_declaration) + + +# Call this method if the line is directly inside of a namespace. +# If the line above is blank (excluding comments) or the start of +# an inner namespace, it cannot be indented. +def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum, + error): + line = raw_lines_no_comments[linenum] + if Match(r'^\s+', line): + error(filename, linenum, 'runtime/indentation_namespace', 4, + 'Do not indent within a namespace') + + +def ProcessLine(filename, file_extension, clean_lines, line, + include_state, function_state, nesting_state, error, + extra_check_functions=[]): + """Processes a single line in the file. + + Args: + filename: Filename of the file that is being processed. + file_extension: The extension (dot not included) of the file. + clean_lines: An array of strings, each representing a line of the file, + with comments stripped. + line: Number of line being processed. + include_state: An _IncludeState instance in which the headers are inserted. + function_state: A _FunctionState instance which counts function lines, etc. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: A callable to which errors are reported, which takes 4 arguments: + filename, line number, error level, and message + extra_check_functions: An array of additional check functions that will be + run on each source line. Each function takes 4 + arguments: filename, clean_lines, line, error + """ + raw_lines = clean_lines.raw_lines + ParseNolintSuppressions(filename, raw_lines[line], line, error) + nesting_state.Update(filename, clean_lines, line, error) + CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, + error) + if nesting_state.InAsmBlock(): return + CheckForFunctionLengths(filename, clean_lines, line, function_state, error) + CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) + CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) + CheckLanguage(filename, clean_lines, line, file_extension, include_state, + nesting_state, error) + CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) + CheckForNonStandardConstructs(filename, clean_lines, line, + nesting_state, error) + CheckVlogArguments(filename, clean_lines, line, error) + CheckPosixThreading(filename, clean_lines, line, error) + CheckInvalidIncrement(filename, clean_lines, line, error) + CheckMakePairUsesDeduction(filename, clean_lines, line, error) + CheckDefaultLambdaCaptures(filename, clean_lines, line, error) + CheckRedundantVirtual(filename, clean_lines, line, error) + CheckRedundantOverrideOrFinal(filename, clean_lines, line, error) + for check_fn in extra_check_functions: + check_fn(filename, clean_lines, line, error) + +def FlagCxx11Features(filename, clean_lines, linenum, error): + """Flag those c++11 features that we only allow in certain places. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Flag unapproved C++11 headers. + include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) + if include and include.group(1) in ('cfenv', + 'condition_variable', + 'fenv.h', + 'future', + 'mutex', + 'thread', + 'chrono', + 'ratio', + 'regex', + 'system_error', + ): + error(filename, linenum, 'build/c++11', 5, + ('<%s> is an unapproved C++11 header.') % include.group(1)) + + # The only place where we need to worry about C++11 keywords and library + # features in preprocessor directives is in macro definitions. + if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return + + # These are classes and free functions. The classes are always + # mentioned as std::*, but we only catch the free functions if + # they're not found by ADL. They're alphabetical by header. + for top_name in ( + # type_traits + 'alignment_of', + 'aligned_union', + ): + if Search(r'\bstd::%s\b' % top_name, line): + error(filename, linenum, 'build/c++11', 5, + ('std::%s is an unapproved C++11 class or function. Send c-style ' + 'an example of where it would make your code more readable, and ' + 'they may let you use it.') % top_name) + + +def ProcessFileData(filename, file_extension, lines, error, + extra_check_functions=[]): + """Performs lint checks and reports any errors to the given error function. + + Args: + filename: Filename of the file that is being processed. + file_extension: The extension (dot not included) of the file. + lines: An array of strings, each representing a line of the file, with the + last element being empty if the file is terminated with a newline. + error: A callable to which errors are reported, which takes 4 arguments: + filename, line number, error level, and message + extra_check_functions: An array of additional check functions that will be + run on each source line. Each function takes 4 + arguments: filename, clean_lines, line, error + """ + lines = (['// marker so line numbers and indices both start at 1'] + lines + + ['// marker so line numbers end in a known way']) + + include_state = _IncludeState() + function_state = _FunctionState() + nesting_state = NestingState() + + ResetNolintSuppressions() + + CheckForCopyright(filename, lines, error) + + RemoveMultiLineComments(filename, lines, error) + clean_lines = CleansedLines(lines) + + if file_extension == 'h': + CheckForHeaderGuard(filename, clean_lines, error) + + for line in xrange(clean_lines.NumLines()): + ProcessLine(filename, file_extension, clean_lines, line, + include_state, function_state, nesting_state, error, + extra_check_functions) + FlagCxx11Features(filename, clean_lines, line, error) + nesting_state.CheckCompletedBlocks(filename, error) + + CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) + + # Check that the .cc file has included its header if it exists. + if file_extension == 'cc': + CheckHeaderFileIncluded(filename, include_state, error) + + # We check here rather than inside ProcessLine so that we see raw + # lines rather than "cleaned" lines. + CheckForBadCharacters(filename, lines, error) + + CheckForNewlineAtEOF(filename, lines, error) + +def ProcessConfigOverrides(filename): + """ Loads the configuration files and processes the config overrides. + + Args: + filename: The name of the file being processed by the linter. + + Returns: + False if the current |filename| should not be processed further. + """ + + abs_filename = os.path.abspath(filename) + cfg_filters = [] + keep_looking = True + while keep_looking: + abs_path, base_name = os.path.split(abs_filename) + if not base_name: + break # Reached the root directory. + + cfg_file = os.path.join(abs_path, "CPPLINT.cfg") + abs_filename = abs_path + if not os.path.isfile(cfg_file): + continue + + try: + with open(cfg_file) as file_handle: + for line in file_handle: + line, _, _ = line.partition('#') # Remove comments. + if not line.strip(): + continue + + name, _, val = line.partition('=') + name = name.strip() + val = val.strip() + if name == 'set noparent': + keep_looking = False + elif name == 'filter': + cfg_filters.append(val) + elif name == 'exclude_files': + # When matching exclude_files pattern, use the base_name of + # the current file name or the directory name we are processing. + # For example, if we are checking for lint errors in /foo/bar/baz.cc + # and we found the .cfg file at /foo/CPPLINT.cfg, then the config + # file's "exclude_files" filter is meant to be checked against "bar" + # and not "baz" nor "bar/baz.cc". + if base_name: + pattern = re.compile(val) + if pattern.match(base_name): + sys.stderr.write('Ignoring "%s": file excluded by "%s". ' + 'File path component "%s" matches ' + 'pattern "%s"\n' % + (filename, cfg_file, base_name, val)) + return False + elif name == 'linelength': + global _line_length + try: + _line_length = int(val) + except ValueError: + sys.stderr.write('Line length must be numeric.') + else: + sys.stderr.write( + 'Invalid configuration option (%s) in file %s\n' % + (name, cfg_file)) + + except IOError: + sys.stderr.write( + "Skipping config file '%s': Can't open for reading\n" % cfg_file) + keep_looking = False + + # Apply all the accumulated filters in reverse order (top-level directory + # config options having the least priority). + for filter in reversed(cfg_filters): + _AddFilters(filter) + + return True + + +def ProcessFile(filename, vlevel, extra_check_functions=[]): + """Does google-lint on a single file. + + Args: + filename: The name of the file to parse. + + vlevel: The level of errors to report. Every error of confidence + >= verbose_level will be reported. 0 is a good default. + + extra_check_functions: An array of additional check functions that will be + run on each source line. Each function takes 4 + arguments: filename, clean_lines, line, error + """ + + _SetVerboseLevel(vlevel) + _BackupFilters() + + if not ProcessConfigOverrides(filename): + _RestoreFilters() + return + + lf_lines = [] + crlf_lines = [] + try: + # Support the UNIX convention of using "-" for stdin. Note that + # we are not opening the file with universal newline support + # (which codecs doesn't support anyway), so the resulting lines do + # contain trailing '\r' characters if we are reading a file that + # has CRLF endings. + # If after the split a trailing '\r' is present, it is removed + # below. + if filename == '-': + lines = codecs.StreamReaderWriter(sys.stdin, + codecs.getreader('utf8'), + codecs.getwriter('utf8'), + 'replace').read().split('\n') + else: + lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') + + # Remove trailing '\r'. + # The -1 accounts for the extra trailing blank line we get from split() + for linenum in range(len(lines) - 1): + if lines[linenum].endswith('\r'): + lines[linenum] = lines[linenum].rstrip('\r') + crlf_lines.append(linenum + 1) + else: + lf_lines.append(linenum + 1) + + except IOError: + sys.stderr.write( + "Skipping input '%s': Can't open for reading\n" % filename) + _RestoreFilters() + return + + # Note, if no dot is found, this will give the entire filename as the ext. + file_extension = filename[filename.rfind('.') + 1:] + + # When reading from stdin, the extension is unknown, so no cpplint tests + # should rely on the extension. + if filename != '-' and file_extension not in _valid_extensions: + sys.stderr.write('Ignoring %s; not a valid file name ' + '(%s)\n' % (filename, ', '.join(_valid_extensions))) + else: + ProcessFileData(filename, file_extension, lines, Error, + extra_check_functions) + + # If end-of-line sequences are a mix of LF and CR-LF, issue + # warnings on the lines with CR. + # + # Don't issue any warnings if all lines are uniformly LF or CR-LF, + # since critique can handle these just fine, and the style guide + # doesn't dictate a particular end of line sequence. + # + # We can't depend on os.linesep to determine what the desired + # end-of-line sequence should be, since that will return the + # server-side end-of-line sequence. + #if lf_lines and crlf_lines: + # # Warn on every line with CR. An alternative approach might be to + # # check whether the file is mostly CRLF or just LF, and warn on the + # # minority, we bias toward LF here since most tools prefer LF. + # for linenum in crlf_lines: + # Error(filename, linenum, 'whitespace/newline', 1, + # 'Unexpected \\r (^M) found; better to use only \\n') + + sys.stderr.write('Done processing %s\n' % filename) + _RestoreFilters() + + +def PrintUsage(message): + """Prints a brief usage string and exits, optionally with an error message. + + Args: + message: The optional error message. + """ + sys.stderr.write(_USAGE) + if message: + sys.exit('\nFATAL ERROR: ' + message) + else: + sys.exit(1) + + +def PrintCategories(): + """Prints a list of all the error-categories used by error messages. + + These are the categories used to filter messages via --filter. + """ + sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) + sys.exit(0) + + +def ParseArguments(args): + """Parses the command line arguments. + + This may set the output format and verbosity level as side-effects. + + Args: + args: The command line arguments: + + Returns: + The list of filenames to lint. + """ + try: + (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', + 'counting=', + 'filter=', + 'root=', + 'linelength=', + 'extensions=']) + except getopt.GetoptError: + PrintUsage('Invalid arguments.') + + verbosity = _VerboseLevel() + output_format = _OutputFormat() + # Default filters for Tizen Platform + filters = '-build/class,-build/c++11,' + \ + '-build/deprecated,-build/endif_comment,-build/explicit_make_pair,-build/forward_decl,' + \ + '-build/header_guard,-build/include,-build/include_alpha,-build/include_order,' + \ + '-build/include_what_you_use,-build/namespaces,-build/printf_format,-build/storage_class,' + \ + '-legal/copyright,-readability/alt_tokens,-readability/casting,-readability/check,' + \ + '-readability/constructors,-readability/fn_size,-readability/function,-readability/inheritance,-readability/multiline_comment,' + \ + '-readability/multiline_string,-readability/namespace,-readability/nolint,-readability/nul,-readability/strings,' + \ + '-readability/todo,-readability/utf8,-runtime/arrays,-runtime/casting,-runtime/explicit,' + \ + '-runtime/int,-runtime/init,-runtime/invalid_increment,-runtime/member_string_references,-runtime/memset,' + \ + '-runtime/indentation_namespace,-runtime/operator,-runtime/printf,-runtime/printf_format,-runtime/references,' + \ + '-runtime/string,-runtime/threadsafe_fn,-runtime/vlog,-whitespace/comments,' + \ + '-whitespace/empty_conditional_body,-whitespace/empty_loop_body,-whitespace/ending_newline,-whitespace/forcolon,' + \ + '-whitespace/indent,-whitespace/line_length,-whitespace/semicolon,-whitespace/tab,' + \ + '-whitespace/todo' + counting_style = '' + + for (opt, val) in opts: + if opt == '--help': + PrintUsage(None) + elif opt == '--output': + if val not in ('emacs', 'vs7', 'eclipse'): + PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.') + output_format = val + elif opt == '--verbose': + verbosity = int(val) + elif opt == '--filter': + filters = val + if not filters: + PrintCategories() + elif opt == '--counting': + if val not in ('total', 'toplevel', 'detailed'): + PrintUsage('Valid counting options are total, toplevel, and detailed') + counting_style = val + elif opt == '--root': + global _root + _root = val + elif opt == '--linelength': + global _line_length + try: + _line_length = int(val) + except ValueError: + PrintUsage('Line length must be digits.') + elif opt == '--extensions': + global _valid_extensions + try: + _valid_extensions = set(val.split(',')) + except ValueError: + PrintUsage('Extensions must be comma seperated list.') + + if not filenames: + PrintUsage('No files were specified.') + + _SetOutputFormat(output_format) + _SetVerboseLevel(verbosity) + _SetFilters(filters) + _SetCountingStyle(counting_style) + + return filenames + + +def main(): + filenames = ParseArguments(sys.argv[1:]) + + # Change stderr to write with replacement characters so we don't die + # if we try to print something containing non-ASCII characters. + sys.stderr = codecs.StreamReaderWriter(sys.stderr, + codecs.getreader('utf8'), + codecs.getwriter('utf8'), + 'replace') + + _cpplint_state.ResetErrorCounts() + for filename in filenames: + ProcessFile(filename, _cpplint_state.verbose_level) + _cpplint_state.PrintErrorCounts() + + sys.exit(_cpplint_state.error_count > 0) + + +if __name__ == '__main__': + main() diff --git a/tools/codestyle/cpplint_tizen_dir.sh b/tools/codestyle/cpplint_tizen_dir.sh new file mode 100755 index 0000000..465a5cc --- /dev/null +++ b/tools/codestyle/cpplint_tizen_dir.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +patch_cpp=`dirname $0`/cpplint_tizen_160919.py + +# check rule to cpp +for i in `find $1 -name "*.cpp" -o -name "*.cc"` +do + python $patch_cpp $i +done + +for i in `find $1 -name "*.h"` +do + python $patch_cpp $i +done diff --git a/tools/codestyle/eslint_config_mandatory_length90.js b/tools/codestyle/eslint_config_mandatory_length90.js new file mode 100644 index 0000000..a09f75b --- /dev/null +++ b/tools/codestyle/eslint_config_mandatory_length90.js @@ -0,0 +1,29 @@ +module.exports = { + 'env': {'browser': true, 'es6': true}, + 'parserOptions': {'sourceType': 'module'}, + 'rules': { + // mandatory + 'comma-dangle': [ + 'error', { + 'arrays': 'never', + 'objects': 'never', + 'imports': 'never', + 'exports': 'never', + 'functions': 'ignore', + } + ], + // mandatory + 'indent': ['error', 2], + // mandatory + 'max-len': ['error', {'code': 90}], + // mandatory + 'no-extra-semi': ['error'], + // mandatory + 'operator-linebreak': + ['error', 'after', {'overrides': {'?': 'before', ':': 'before'}}], + // mandatory + 'quotes': ['error', 'single'], + // mandatory + 'semi': ['error', 'always'] + } +}; diff --git a/tools/codestyle/js_clang_formatter.sh b/tools/codestyle/js_clang_formatter.sh new file mode 100755 index 0000000..1b55c3c --- /dev/null +++ b/tools/codestyle/js_clang_formatter.sh @@ -0,0 +1,71 @@ +#!/bin/bash + +command -v fixjsstyle >/dev/null 2>&1 || { + echo >&2 "fixjsstyle is required, but it's not installed."; + echo "-------------------------------------------------------------------------------------"; + echo "Related webpage: https://developers.google.com/closure/utilities/docs/linter_howto"; + echo "To install Closure Linter on Debian/Ubuntu, execute the following commands:"; + echo " sudo apt-get install python-pip"; + echo " sudo pip install https://github.com/google/closure-linter/zipball/master"; + echo "-------------------------------------------------------------------------------------"; + exit 1; + } + +# https://clangformat.com/ +command -v clang-format >/dev/null 2>&1 || { + echo >&2 "clang-format is required, but it's not installed"; + echo "-------------------------------------------------------------------------------------"; + echo "To install clang-format on Debian/Ubuntu, execute the following commands." + echo " sudo apt-get install clang-format-3.9" + echo " sudo ln -s /usr/bin/clang-format-3.9 /usr/bin/clang-format" + echo "-------------------------------------------------------------------------------------"; + exit 1; + } + + +CONFIG='{ +BasedOnStyle: Google, +Language: JavaScript, +UseTab: Never, +IndentWidth: 2, +ColumnLimit: 90, +AllowShortFunctionsOnASingleLine: false, +PenaltyExcessCharacter: 1000, +}' + +formatJS() { + ls $1/*.js &>/dev/null + if [[ $? -eq 0 ]]; then + printf "." + # using fixjsstyle for fixing some js issues + fixjsstyle --nojsdoc --strict $1/*.js &> /dev/null + # using clang-format for adjusting code style + clang-format -i -style="$CONFIG" $1/*.js &> /dev/null + + # some issues could still appear after first style fixes, + # repeating the same operations to fix them also + fixjsstyle --nojsdoc --strict $1/*.js &> /dev/null + clang-format -i -style="$CONFIG" $1/*.js &> /dev/null + fi +} + +checkDirectoriesRecursive() { + dirs=$(find $1 -type d) + for d in $dirs; + do + if [[ -d $d ]]; then + formatJS $d; + fi + done +} + +printf "JS reformatting: "; +if [[ $# -eq 0 ]]; then + checkDirectoriesRecursive src/ +else + checkDirectoriesRecursive $1 +fi +echo " DONE JS reformatting" + + + -- 2.7.4 From feb4fd71c2ea8e8a7440f7e5942c097748e524e4 Mon Sep 17 00:00:00 2001 From: Szymon Jastrzebski Date: Mon, 18 Sep 2017 11:30:34 +0200 Subject: [PATCH 03/16] [PROJECT] Refactoring entering logs into ScopeLogger Removing logs in trivial function and adding when they are missed will be part of another commit PS2 Rebase PS3 Change some left Loggers PS4 After using clang PS5 Utilizing changes in ScopeLogger PS6 Cleaning up PS8 Adding missing logs - not formatted PS9 Clang PS10 Rebase [Verification] Code compiles 10 random packages has 100% passrate: alarm, systemsetting, systeminfo, security, content, filesystem, iotcon, push, capability, privillege Change-Id: I7972fee44dd13277d9ef7693433aad7b0321dd68 Signed-off-by: Szymon Jastrzebski Signed-off-by: Michal Bistyga --- src/account/account_instance.cc | 40 ++--- src/account/account_manager.cc | 36 ++--- src/alarm/alarm_instance.cc | 4 +- src/alarm/alarm_manager.cc | 20 +-- src/alarm/alarm_utils.cc | 4 +- src/application/application.cc | 2 +- src/application/application_extension.cc | 8 +- src/application/application_instance.cc | 48 +++--- src/application/application_manager.cc | 94 ++++++------ src/application/application_utils.cc | 20 ++- src/application/requested_application_control.cc | 14 +- src/archive/archive_callback_data.cc | 116 +++++--------- src/archive/archive_extension.cc | 8 +- src/archive/archive_file.cc | 58 +++---- src/archive/archive_file_entry.cc | 5 +- src/archive/archive_instance.cc | 34 ++--- src/archive/archive_manager.cc | 16 +- src/archive/archive_utils.cc | 22 +-- src/archive/filesystem_file.cc | 4 +- src/archive/filesystem_node.cc | 44 +++--- src/archive/filesystem_path.cc | 7 +- src/archive/un_zip.cc | 24 +-- src/archive/un_zip_extract_request.cc | 24 +-- src/archive/zip.cc | 14 +- src/archive/zip_add_request.cc | 20 +-- src/badge/badge_instance.cc | 12 +- src/badge/badge_manager.cc | 14 +- src/bluetooth/bluetooth_adapter.cc | 78 ++++++---- src/bluetooth/bluetooth_class.cc | 6 +- src/bluetooth/bluetooth_device.cc | 13 +- src/bluetooth/bluetooth_gatt_service.cc | 46 +++--- src/bluetooth/bluetooth_health_application.cc | 4 +- src/bluetooth/bluetooth_health_channel.cc | 8 +- src/bluetooth/bluetooth_health_profile_handler.cc | 22 +-- src/bluetooth/bluetooth_instance.cc | 17 ++- src/bluetooth/bluetooth_le_adapter.cc | 50 +++--- src/bluetooth/bluetooth_le_device.cc | 26 ++-- src/bluetooth/bluetooth_service_handler.cc | 2 +- src/bluetooth/bluetooth_socket.cc | 9 +- src/bookmark/bookmark_instance.cc | 20 +-- src/calendar/calendar.cc | 22 ++- src/calendar/calendar_instance.cc | 60 ++++---- src/calendar/calendar_item.cc | 83 +++++----- src/calendar/calendar_manager.cc | 14 +- src/calendar/calendar_plugin.cc | 3 + src/calendar/calendar_record.cc | 48 +++--- src/callhistory/callhistory.cc | 29 ++-- src/callhistory/callhistory_instance.cc | 19 +-- src/callhistory/callhistory_utils.cc | 29 ++-- src/common/GDBus/connection.cpp | 4 +- src/common/XW_Extension.cc | 6 +- src/common/converter.cc | 2 +- src/common/current_application.cc | 18 +-- src/common/extension.cc | 66 ++++---- src/common/filesystem/filesystem_provider.cc | 22 +-- .../filesystem/filesystem_provider_deviced.cc | 28 ++-- .../filesystem/filesystem_provider_storage.cc | 26 ++-- src/common/filesystem/filesystem_storage.cc | 16 +- src/common/filter-utils.cc | 20 +-- src/common/platform_result.cc | 4 +- src/common/tools.cc | 24 +-- src/contact/addressbook.cc | 32 ++-- src/contact/contact_instance.cc | 59 +++++++- src/contact/contact_manager.cc | 32 ++-- src/contact/contact_search_engine.cc | 42 +++--- src/contact/contact_util.cc | 75 ++++----- src/contact/person.cc | 10 +- src/content/content_filter.cc | 14 +- src/content/content_instance.cc | 77 +++++----- src/content/content_manager.cc | 94 ++++++------ src/datacontrol/datacontrol_instance.cc | 50 +++--- src/download/download_instance.cc | 40 ++--- src/exif/exif_gps_location.cc | 48 +++--- src/exif/exif_information.cc | 79 ++-------- src/exif/exif_instance.cc | 16 +- src/exif/exif_tag_saver.cc | 22 +-- src/exif/exif_util.cc | 24 ++- src/exif/get_exif_info.cc | 15 +- src/exif/jpeg_file.cc | 22 +-- src/exif/rational.cc | 9 +- src/feedback/feedback_instance.cc | 10 +- src/feedback/feedback_manager.cc | 19 ++- src/filesystem/filesystem_file.cc | 9 +- src/filesystem/filesystem_instance.cc | 113 +++++++------- src/filesystem/filesystem_manager.cc | 50 +++--- src/filesystem/filesystem_stat.cc | 7 +- src/filesystem/filesystem_utils.cc | 4 +- .../humanactivitymonitor_instance.cc | 26 ++-- .../humanactivitymonitor_manager.cc | 17 +-- src/inputdevice/inputdevice_instance.cc | 4 +- src/iotcon/iotcon_instance.cc | 22 ++- src/iotcon/iotcon_manager.cc | 2 + src/iotcon/iotcon_server_manager.cc | 10 +- src/iotcon/iotcon_utils.cc | 146 ++++++++++-------- src/keymanager/keymanager_instance.cc | 21 ++- src/mediacontroller/mediacontroller_client.cc | 36 ++--- src/mediacontroller/mediacontroller_instance.cc | 50 +++--- src/mediacontroller/mediacontroller_server.cc | 30 ++-- src/mediacontroller/mediacontroller_types.cc | 12 +- src/mediakey/mediakey_instance.cc | 14 +- src/mediakey/mediakey_manager.cc | 10 +- src/messageport/messageport_instance.cc | 18 +-- src/messaging/DBus/EmailSignalProxy.cpp | 2 + src/messaging/DBus/LoadAttachmentProxy.cpp | 9 ++ src/messaging/DBus/LoadBodyProxy.cpp | 5 + src/messaging/DBus/MessageProxy.cpp | 16 +- src/messaging/DBus/SendProxy.cpp | 5 +- src/messaging/DBus/SyncProxy.cpp | 8 + src/messaging/MsgCommon/AbstractFilter.cpp | 5 + src/messaging/MsgCommon/Any.cpp | 2 + src/messaging/MsgCommon/AttributeFilter.cpp | 3 + src/messaging/MsgCommon/AttributeRangeFilter.cpp | 2 + src/messaging/MsgCommon/CompositeFilter.cpp | 2 + src/messaging/MsgCommon/FilterIterator.cpp | 6 + src/messaging/MsgCommon/SortMode.cpp | 5 +- src/messaging/callback_user_data.cc | 20 +-- src/messaging/change_listener_container.cc | 56 +++---- src/messaging/conversation_callback_data.cc | 4 +- src/messaging/conversations_change_callback.cc | 12 +- src/messaging/email_manager.cc | 77 +++++----- src/messaging/find_msg_callback_user_data.cc | 4 +- src/messaging/folders_callback_data.cc | 3 +- src/messaging/folders_change_callback.cc | 12 +- src/messaging/message.cc | 77 +++++----- src/messaging/message_attachment.cc | 18 +-- src/messaging/message_body.cc | 6 +- src/messaging/message_callback_user_data.cc | 4 +- src/messaging/message_conversation.cc | 14 +- src/messaging/message_email.cc | 18 +-- src/messaging/message_folder.cc | 10 +- src/messaging/message_mms.cc | 12 +- src/messaging/message_service.cc | 28 ++-- src/messaging/message_service_email.cc | 28 ++-- src/messaging/message_service_short_msg.cc | 14 +- src/messaging/message_sms.cc | 4 +- src/messaging/message_storage.cc | 16 +- src/messaging/message_storage_email.cc | 32 ++-- src/messaging/message_storage_short_msg.cc | 32 ++-- src/messaging/messages_callback_user_data.cc | 6 +- src/messaging/messages_change_callback.cc | 16 +- src/messaging/messaging_database_manager.cc | 40 ++--- src/messaging/messaging_extension.cc | 6 +- src/messaging/messaging_instance.cc | 42 +++--- src/messaging/messaging_manager.cc | 13 +- src/messaging/messaging_util.cc | 80 +++++----- src/messaging/short_message_manager.cc | 47 +++--- .../networkbearerselection_instance.cc | 18 +-- .../networkbearerselection_manager.cc | 41 ++--- src/nfc/aid_data.cc | 4 +- src/nfc/nfc_adapter.cc | 139 ++++++++--------- src/nfc/nfc_extension.cc | 6 +- src/nfc/nfc_instance.cc | 110 +++++++------- src/nfc/nfc_message_utils.cc | 62 ++++---- src/nfc/nfc_util.cc | 34 ++--- src/notification/notification_instance.cc | 20 +-- src/notification/notification_manager.cc | 22 +-- src/notification/status_notification.cc | 76 +++++----- src/package/package_extension.cc | 8 +- src/package/package_info_provider.cc | 19 +-- src/package/package_instance.cc | 41 ++--- src/power/power_extension.cc | 2 + src/power/power_instance.cc | 22 +-- src/power/power_manager.cc | 34 ++--- src/power/power_platform_proxy.cc | 18 +-- src/preference/preference_instance.cc | 1 + src/preference/preference_manager.cc | 3 + src/push/push_instance.cc | 33 ++-- src/push/push_manager.cc | 46 +++--- src/push/push_manager_common.cc | 10 +- src/radio/radio_instance.cc | 38 +++-- src/radio/radio_manager.cc | 62 ++++---- src/secureelement/secureelement_instance.cc | 5 + src/sensor/sensor_instance.cc | 18 +-- src/sensor/sensor_service.cc | 104 +++++++------ src/sound/sound_instance.cc | 28 ++-- src/sound/sound_manager.cc | 54 ++++--- src/systeminfo/systeminfo-utils.cpp | 14 +- src/systeminfo/systeminfo_device_capability.cc | 25 ++- src/systeminfo/systeminfo_instance.cc | 28 ++-- src/systeminfo/systeminfo_manager.cc | 167 +++++++++++---------- src/systeminfo/systeminfo_properties_manager.cc | 56 +++---- src/systeminfo/systeminfo_sim_details_manager.cc | 29 ++-- src/systemsetting/systemsetting_instance.cc | 18 +-- src/time/time_extension.cc | 8 +- src/time/time_instance.cc | 44 +++--- src/time/time_manager.cc | 17 +-- src/time/time_utils.cc | 24 +-- src/tvinputdevice/tvinputdevice_instance.cc | 4 +- src/utils/utils_extension.cc | 8 +- src/utils/utils_instance.cc | 12 +- src/websetting/websetting_extension.cc | 6 +- src/widgetservice/widgetservice_instance.cc | 6 +- 192 files changed, 2757 insertions(+), 2554 deletions(-) mode change 100755 => 100644 src/filesystem/filesystem_utils.cc diff --git a/src/account/account_instance.cc b/src/account/account_instance.cc index 903b262..7d75444 100644 --- a/src/account/account_instance.cc +++ b/src/account/account_instance.cc @@ -47,7 +47,7 @@ const std::string kPrivilegeAccountWrite = "http://tizen.org/privilege/account.w } AccountInstance::AccountInstance() { - LoggerD("Enter"); + ScopeLogger(); manager_ = new AccountManager; subscribe_ = NULL; @@ -74,7 +74,7 @@ AccountInstance::AccountInstance() { } AccountInstance::~AccountInstance() { - LoggerD("Enter"); + ScopeLogger(); delete manager_; if (subscribe_) { account_unsubscribe_notification(subscribe_); @@ -82,12 +82,12 @@ AccountInstance::~AccountInstance() { } AccountManager* AccountInstance::GetAccountManager() { - LoggerD("Enter"); + ScopeLogger(); return manager_; } void AccountInstance::AccountSetExtendedData(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountWrite, &out); @@ -103,7 +103,7 @@ void AccountInstance::AccountSetExtendedData(const picojson::value& args, picojs } void AccountInstance::AccountGetExtendedData(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); @@ -114,11 +114,13 @@ void AccountInstance::AccountGetExtendedData(const picojson::value& args, picojs int callback_id = static_cast(args.get("callbackId").get()); auto get_extended_data = [this, account_id](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function, get_extended_dat"); this->manager_->GetExtendedData(account_id, result->get()); }; auto get_extended_data_result = [this, callback_id](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function, get_extended_dat_result"); result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; Instance::PostMessage(this, result->serialize().c_str()); @@ -134,7 +136,7 @@ void AccountInstance::AccountGetExtendedData(const picojson::value& args, picojs void AccountInstance::AccountGetExtendedDataSync(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); @@ -148,25 +150,25 @@ void AccountInstance::AccountGetExtendedDataSync(const picojson::value& args, } void AccountInstance::AccountManagerAdd(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountWrite, &out); manager_->AddAccount(args, out); } void AccountInstance::AccountManagerRemove(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountWrite, &out); manager_->RemoveAccount(args, out); } void AccountInstance::AccountManagerUpdate(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountWrite, &out); manager_->UpdateAccount(args, out); } void AccountInstance::AccountManagerGetAccount(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); @@ -179,7 +181,7 @@ void AccountInstance::AccountManagerGetAccount(const picojson::value& args, pico void AccountInstance::AccountManagerGetAccounts(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); @@ -191,10 +193,12 @@ void AccountInstance::AccountManagerGetAccounts(const picojson::value& args, LoggerD("application ID: [%s]", application_id.c_str()); auto get_accounts = [this, application_id](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function get_accounts"); this->manager_->GetAccountsInfo(application_id, result->get()); }; auto get_accounts_result = [this, callback_id](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function, get_accounts_result"); result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; Instance::PostMessage(this, result->serialize().c_str()); @@ -209,7 +213,7 @@ void AccountInstance::AccountManagerGetAccounts(const picojson::value& args, void AccountInstance::AccountManagerGetProvider(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); @@ -221,7 +225,7 @@ void AccountInstance::AccountManagerGetProvider(const picojson::value& args, void AccountInstance::AccountManagerGetProviders(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); @@ -234,10 +238,12 @@ void AccountInstance::AccountManagerGetProviders(const picojson::value& args, LoggerD("capability [%s]", capability.c_str()); auto get_providers = [this, capability](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function, get_providers"); this->manager_->GetProvidersInfo(capability, result->get()); }; auto get_providers_result = [this, callback_id](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function, get_providers_result"); result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; Instance::PostMessage(this, result->serialize().c_str()); @@ -251,13 +257,13 @@ void AccountInstance::AccountManagerGetProviders(const picojson::value& args, } void AccountInstance::InvokeListener(picojson::object& param) { - LoggerD("Enter"); + ScopeLogger(); picojson::value result = picojson::value(param); Instance::PostMessage(this, result.serialize().c_str()); } static bool AccountEventCb(const char* event_type, int account_id, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); AccountInstance* instance = static_cast(user_data); if (!instance) { @@ -293,7 +299,7 @@ static bool AccountEventCb(const char* event_type, int account_id, void* user_da void AccountInstance::AccountManagerAddAccountListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); if (!subscribe_) { @@ -321,7 +327,7 @@ void AccountInstance::AccountManagerAddAccountListener(const picojson::value& ar void AccountInstance::AccountManagerRemoveAccountListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAccountRead, &out); diff --git a/src/account/account_manager.cc b/src/account/account_manager.cc index b409b89..ca685a8 100644 --- a/src/account/account_manager.cc +++ b/src/account/account_manager.cc @@ -32,7 +32,7 @@ using common::tools::ReportError; namespace { static bool ProviderCapabilitiesCb(char* app_id, char* key, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::array* array_data = static_cast(user_data); if (!array_data) { @@ -45,7 +45,7 @@ static bool ProviderCapabilitiesCb(char* app_id, char* key, void* user_data) { } static bool AccountProvidersGetCb(account_type_h provider, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::array* array_data = static_cast(user_data); if (!array_data) { @@ -62,7 +62,7 @@ static bool AccountProvidersGetCb(account_type_h provider, void* user_data) { } static bool GetAccountsCallback(account_h handle, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::array* array_data = static_cast(user_data); if (!array_data) { @@ -81,7 +81,7 @@ static bool GetAccountsCallback(account_h handle, void* user_data) { } static bool GetCustomAllCallback(char* key, char* value, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::array* array_data = static_cast(user_data); if (!array_data) { @@ -103,11 +103,11 @@ static bool GetCustomAllCallback(char* key, char* value, void* user_data) { } // namespace AccountManager::AccountManager() { - LoggerD("Enter"); + ScopeLogger(); } AccountManager::~AccountManager() { - LoggerD("Enter"); + ScopeLogger(); } std::string AccountManager::GetErrorMsg(int error) { @@ -152,7 +152,7 @@ std::string AccountManager::GetErrorMsg(int error) { } void AccountManager::GetAccountsInfo(const std::string& application_id, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); picojson::array array_data; int ret = ACCOUNT_ERROR_NONE; @@ -174,7 +174,7 @@ void AccountManager::GetAccountsInfo(const std::string& application_id, picojson } void AccountManager::GetAccountInfo(int account_id, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); account_h account = NULL; SCOPE_EXIT { @@ -211,7 +211,7 @@ void AccountManager::GetAccountInfo(int account_id, picojson::object& out) { } bool AccountManager::GetProviderInfo(const std::string& provider_id, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); account_type_h provider = NULL; SCOPE_EXIT { @@ -254,7 +254,7 @@ bool AccountManager::GetProviderInfo(const std::string& provider_id, picojson::o } bool AccountManager::ConvertAccountToObject(account_h account, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); char* provider_id = NULL; char* icon_path = NULL; @@ -307,7 +307,7 @@ bool AccountManager::ConvertAccountToObject(account_h account, picojson::object& } bool AccountManager::ConvertProviderToObject(account_type_h provider, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); char* provider_id = NULL; char* display_name = NULL; @@ -373,7 +373,7 @@ bool AccountManager::ConvertProviderToObject(account_type_h provider, picojson:: } void AccountManager::GetProvidersInfo(const std::string& capability, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); picojson::array array_data; int ret = ACCOUNT_ERROR_NONE; @@ -396,7 +396,7 @@ void AccountManager::GetProvidersInfo(const std::string& capability, picojson::o void AccountManager::GetExtendedData(int account_id, const std::string& key, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); account_h account = nullptr; SCOPE_EXIT { @@ -433,7 +433,7 @@ void AccountManager::GetExtendedData(int account_id, const std::string& key, } void AccountManager::GetExtendedData(int account_id, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); account_h account = nullptr; SCOPE_EXIT { @@ -464,7 +464,7 @@ void AccountManager::GetExtendedData(int account_id, picojson::object& out) { void AccountManager::SetExtendedData(int account_id, const std::string& key, const std::string& value, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); account_h account = nullptr; SCOPE_EXIT { @@ -499,7 +499,7 @@ void AccountManager::SetExtendedData(int account_id, const std::string& key, } void AccountManager::AddAccount(const picojson::value& data, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); account_h account_handle = NULL; int account_id; @@ -535,7 +535,7 @@ void AccountManager::AddAccount(const picojson::value& data, picojson::object& o } void AccountManager::RemoveAccount(const picojson::value& data, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); int account_id = static_cast(data.get("accountId").get()); int ret = account_delete_from_db_by_id(account_id); @@ -548,7 +548,7 @@ void AccountManager::RemoveAccount(const picojson::value& data, picojson::object } void AccountManager::UpdateAccount(const picojson::value& data, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); int account_id = static_cast(data.get("accountId").get()); const std::string& user_name = data.get("userName").get(); const std::string& icon_uri = data.get("iconUri").get(); diff --git a/src/alarm/alarm_instance.cc b/src/alarm/alarm_instance.cc index f246c30..1be9f9b 100644 --- a/src/alarm/alarm_instance.cc +++ b/src/alarm/alarm_instance.cc @@ -25,7 +25,7 @@ namespace alarm { using namespace common; AlarmInstance::AlarmInstance() { - LoggerD("Entered"); + ScopeLogger(); using namespace std::placeholders; RegisterSyncHandler("AlarmManager_add", std::bind(&AlarmManager::Add, &manager_, _1, _2)); @@ -43,7 +43,7 @@ AlarmInstance::AlarmInstance() { } AlarmInstance::~AlarmInstance() { - LoggerD("Entered"); + ScopeLogger(); } } // namespace Alarm diff --git a/src/alarm/alarm_manager.cc b/src/alarm/alarm_manager.cc index 9921a27..c9690ce 100644 --- a/src/alarm/alarm_manager.cc +++ b/src/alarm/alarm_manager.cc @@ -65,13 +65,15 @@ const char* kSaturdayShort = "SA"; } AlarmManager::AlarmManager() { + ScopeLogger(); } AlarmManager::~AlarmManager() { + ScopeLogger(); } void AlarmManager::Add(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAlarm, &out); if (!args.contains("alarm")) { @@ -264,7 +266,7 @@ void AlarmManager::Add(const picojson::value& args, picojson::object& out) { } void AlarmManager::Remove(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAlarm, &out); int id = 0; @@ -291,7 +293,7 @@ void AlarmManager::Remove(const picojson::value& args, picojson::object& out) { } void AlarmManager::RemoveAll(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAlarm, &out); int ret = alarm_cancel_all(); @@ -305,7 +307,7 @@ void AlarmManager::RemoveAll(const picojson::value& args, picojson::object& out) } PlatformResult AlarmManager::GetAlarm(int id, picojson::object& obj) { - LoggerD("Entered"); + ScopeLogger(); if (id <= 0) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid id.", @@ -427,7 +429,7 @@ PlatformResult AlarmManager::GetAlarm(int id, picojson::object& obj) { } void AlarmManager::Get(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); int id = 0; @@ -448,7 +450,7 @@ void AlarmManager::Get(const picojson::value& args, picojson::object& out) { } static bool AlarmIterateCB(int alarm_id, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); std::vector* alarm_ids = reinterpret_cast*>(user_data); @@ -457,7 +459,7 @@ static bool AlarmIterateCB(int alarm_id, void* user_data) { } void AlarmManager::GetAll(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); std::vector alarm_ids; int ret = alarm_foreach_registered_alarm(AlarmIterateCB, &alarm_ids); @@ -487,7 +489,7 @@ void AlarmManager::GetAll(const picojson::value& args, picojson::object& out) { } void AlarmManager::GetRemainingSeconds(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); struct tm date; struct tm current; @@ -527,7 +529,7 @@ void AlarmManager::GetRemainingSeconds(const picojson::value& args, picojson::ob } void AlarmManager::GetNextScheduledDate(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); int id = 0; diff --git a/src/alarm/alarm_utils.cc b/src/alarm/alarm_utils.cc index 55c1965..7917e1d 100644 --- a/src/alarm/alarm_utils.cc +++ b/src/alarm/alarm_utils.cc @@ -27,7 +27,7 @@ namespace util { using namespace common; PlatformResult AppControlToService(const picojson::object& obj, app_control_h* app_control) { - LoggerD("Entered"); + ScopeLogger(); const auto it_end = obj.end(); @@ -106,7 +106,7 @@ PlatformResult AppControlToService(const picojson::object& obj, app_control_h* a PlatformResult AppControlToServiceExtraData(const picojson::object& app_obj, app_control_h* app_control) { - LoggerD("Entered"); + ScopeLogger(); const auto it_key = app_obj.find("key"); const auto it_value = app_obj.find("value"); diff --git a/src/application/application.cc b/src/application/application.cc index 6879658..4a3f3ef 100644 --- a/src/application/application.cc +++ b/src/application/application.cc @@ -32,7 +32,7 @@ RequestedApplicationControl& Application::app_control() { } void Application::GetRequestedAppControl(const picojson::value& args, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); const std::string& encoded_bundle = RequestedApplicationControl::GetEncodedBundle(); diff --git a/src/application/application_extension.cc b/src/application/application_extension.cc index 17e25b4..853d08d 100644 --- a/src/application/application_extension.cc +++ b/src/application/application_extension.cc @@ -32,14 +32,14 @@ const char* kApplicationControlData = "tizen.ApplicationControlData"; extern const char kSource_application_api[]; common::Extension* CreateExtension() { - LoggerD("Enter"); + ScopeLogger(); ApplicationExtension* e = new ApplicationExtension(); return e; } ApplicationExtension::ApplicationExtension() { - LoggerD("Enter"); + ScopeLogger(); SetExtensionName(kApplication); SetJavaScriptAPI(kSource_application_api); @@ -49,10 +49,10 @@ ApplicationExtension::ApplicationExtension() { } ApplicationExtension::~ApplicationExtension() { - LoggerD("Enter"); + ScopeLogger(); } common::Instance* ApplicationExtension::CreateInstance() { - LoggerD("Enter"); + ScopeLogger(); return new extension::application::ApplicationInstance(); } diff --git a/src/application/application_instance.cc b/src/application/application_instance.cc index e266380..76f1d32 100644 --- a/src/application/application_instance.cc +++ b/src/application/application_instance.cc @@ -38,7 +38,7 @@ const std::string kPrivilegeApplicationLaunch = "http://tizen.org/privilege/appl using namespace common; ApplicationInstance::ApplicationInstance() : manager_(*this) { - LoggerD("Entered"); + ScopeLogger(); app_id_ = CurrentApplication::GetInstance().GetApplicationId(); LoggerD("app_id: %s", app_id_.c_str()); @@ -90,24 +90,24 @@ ApplicationInstance::ApplicationInstance() : manager_(*this) { } ApplicationInstance::~ApplicationInstance() { - LoggerD("Entered"); + ScopeLogger(); } void ApplicationInstance::GetCurrentApplication(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); manager_.GetCurrentApplication(app_id_, &out); } void ApplicationInstance::GetAppContext(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); manager_.GetAppContext(args, &out); } void ApplicationInstance::GetAppInfo(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); std::string app_id = app_id_; const auto& id = args.get("id"); @@ -119,7 +119,7 @@ void ApplicationInstance::GetAppInfo(const picojson::value& args, picojson::obje } void ApplicationInstance::GetAppCerts(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAppManagerCertificate, &out); @@ -133,7 +133,7 @@ void ApplicationInstance::GetAppCerts(const picojson::value& args, picojson::obj } void ApplicationInstance::GetAppSharedURI(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); std::string app_id = app_id_; const auto& id = args.get("id"); @@ -145,7 +145,7 @@ void ApplicationInstance::GetAppSharedURI(const picojson::value& args, picojson: } void ApplicationInstance::GetAppMetaData(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeApplicationInfo, &out); @@ -160,7 +160,7 @@ void ApplicationInstance::GetAppMetaData(const picojson::value& args, picojson:: void ApplicationInstance::AddAppInfoEventListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); LoggerW( "DEPRECATION WARNING: addAppInfoEventListener() is deprecated and will be removed from next " "release. " @@ -171,7 +171,7 @@ void ApplicationInstance::AddAppInfoEventListener(const picojson::value& args, void ApplicationInstance::RemoveAppInfoEventListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); LoggerW( "DEPRECATION WARNING: removeAppInfoEventListener() is deprecated and will be removed from " "next release. " @@ -183,25 +183,25 @@ void ApplicationInstance::RemoveAppInfoEventListener(const picojson::value& args void ApplicationInstance::GetRequestedAppControl(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); current_application_.GetRequestedAppControl(args, &out); } void ApplicationInstance::ReplyResult(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); current_application_.app_control().ReplyResult(args, &out); } void ApplicationInstance::ReplyFailure(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); current_application_.app_control().ReplyFailure(&out); } void ApplicationInstance::GetSize(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeApplicationInfo, &out); @@ -209,7 +209,7 @@ void ApplicationInstance::GetSize(const picojson::value& args, picojson::object& } void ApplicationInstance::Kill(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeAppManagerKill, &out); @@ -217,7 +217,7 @@ void ApplicationInstance::Kill(const picojson::value& args, picojson::object& ou } void ApplicationInstance::Launch(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeApplicationLaunch, &out); @@ -225,7 +225,7 @@ void ApplicationInstance::Launch(const picojson::value& args, picojson::object& } void ApplicationInstance::LaunchAppControl(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeApplicationLaunch, &out); @@ -233,38 +233,38 @@ void ApplicationInstance::LaunchAppControl(const picojson::value& args, picojson } void ApplicationInstance::FindAppControl(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); manager_.FindAppControl(args); } void ApplicationInstance::GetAppsContext(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); manager_.GetAppsContext(args); } void ApplicationInstance::GetAppsInfo(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); manager_.GetAppsInfo(args); } void ApplicationInstance::BroadcastEvent(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); manager_.BroadcastEventHelper(args, out, false); } void ApplicationInstance::BroadcastTrustedEvent(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); manager_.BroadcastEventHelper(args, out, true); } void ApplicationInstance::AddEventListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const std::string& event_name = args.get("name").get(); @@ -287,7 +287,7 @@ void ApplicationInstance::AddEventListener(const picojson::value& args, picojson } void ApplicationInstance::RemoveEventListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const std::string& event_name = args.get("name").get(); diff --git a/src/application/application_manager.cc b/src/application/application_manager.cc index 4c19abe..6557a50 100644 --- a/src/application/application_manager.cc +++ b/src/application/application_manager.cc @@ -97,16 +97,16 @@ ApplicationManager::ApplicationManager(ApplicationInstance& instance) : pkgmgr_client_handle_(nullptr), pkgmgr_client_uninstall_handle_(nullptr), instance_(instance) { - LoggerD("Enter"); + ScopeLogger(); } ApplicationManager::~ApplicationManager() { - LoggerD("Enter"); + ScopeLogger(); StopAppInfoEventListener(); } void ApplicationManager::GetCurrentApplication(const std::string& app_id, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); // obtain handle to application info pkgmgrinfo_appinfo_h handle; @@ -149,7 +149,7 @@ class TerminateHandler { } void Invoke(const std::shared_ptr& response) { - LoggerD("Entered"); + ScopeLogger(); if (timeout_id_ > 0) { // cancel terminate callback @@ -170,14 +170,14 @@ class TerminateHandler { } void LaunchCheckTerminate() { - LoggerD("Entered"); + ScopeLogger(); timeout_id_ = g_timeout_add(3000, CheckTerminate, this); LoggerD("END"); } private: static gboolean CheckTerminate(gpointer user_data) { - LoggerD("Entered"); + ScopeLogger(); TerminateHandler* that = static_cast(user_data); LoggerD("PID: %d", that->pid_); @@ -221,7 +221,7 @@ class TerminateHandler { void ApplicationManager::AsyncResponse(PlatformResult& result, std::shared_ptr* response) { - LoggerD("Enter"); + ScopeLogger(); LogAndReportError(result, &(*response)->get()); TaskQueue::GetInstance().Async( @@ -232,7 +232,7 @@ void ApplicationManager::AsyncResponse(PlatformResult& result, } void ApplicationManager::Kill(const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); @@ -264,7 +264,7 @@ void ApplicationManager::Kill(const picojson::value& args) { } auto kill = [this, callback_id, context_id]() -> void { - LoggerD("Entered Kill async"); + ScopeLogger("Kill async"); std::shared_ptr response = std::shared_ptr(new picojson::value(picojson::object())); @@ -387,7 +387,7 @@ void ApplicationManager::Kill(const picojson::value& args) { } void ApplicationManager::Launch(const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); int callback_id = -1; const auto& callback = args.get(kCallbackId); @@ -409,6 +409,7 @@ void ApplicationManager::Launch(const picojson::value& args) { const std::string& id = app_id.get(); auto launch = [id](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, launch"); PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); const char* app_id = id.c_str(); const int retry_count = 3; @@ -465,7 +466,7 @@ void ApplicationManager::Launch(const picojson::value& args) { } void ApplicationManager::LaunchAppControl(const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); int callback_id = -1; const auto& callback = args.get(kCallbackId); @@ -518,7 +519,7 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { auto launch = [this, app_control_ptr, app_id, launch_mode_str, reply_callback](const std::shared_ptr& response) -> void { - LoggerD("Entered"); + ScopeLogger("Entered into asynchronous function, launch"); if (!app_id.empty()) { LoggerD("app_id: %s", app_id.c_str()); @@ -651,7 +652,7 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { }; auto launch_response = [this](const std::shared_ptr& response) -> void { - LoggerD("Entered launch_response"); + ScopeLogger("launch_response"); Instance::PostMessage(&this->instance_, response->serialize().c_str()); }; @@ -663,6 +664,7 @@ void ApplicationManager::LaunchAppControl(const picojson::value& args) { // public CAPI did not handling APP_CONTROL_ERROR_APP_NOT_FOUND int app_control_foreach_app_matched_internal(app_control_h app_control, app_control_app_matched_cb callback, void* user_data) { + ScopeLogger(); typedef struct { app_control_h app_control; app_control_app_matched_cb callback; @@ -673,6 +675,9 @@ int app_control_foreach_app_matched_internal(app_control_h app_control, // internal impl of app_control_cb_broker_foreach_app_matched() auto app_control_cb_broker_foreach_app_matched_internal = [](const char* package, void* data) -> int { + ScopeLogger( + "Entered into asynchronous function, app_control_cb_broker_foreach_app_matched_internal's " + "argument"); foreach_context_launchable_app_t_internal* foreach_context; app_control_app_matched_cb app_matched_cb; @@ -725,7 +730,7 @@ int app_control_foreach_app_matched_internal(app_control_h app_control, } void ApplicationManager::FindAppControl(const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); int callback_id = -1; const auto& callback = args.get(kCallbackId); @@ -760,8 +765,10 @@ void ApplicationManager::FindAppControl(const picojson::value& args) { } auto find = [app_control_ptr](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, find"); auto app_control_matched = [](app_control_h app_control, const char* appid, void* user_data) -> bool { + ScopeLogger("Entered into asynchronous function, app_control_matched"); if (nullptr == appid) { LoggerD("appid is NULL"); return false; @@ -814,6 +821,7 @@ void ApplicationManager::FindAppControl(const picojson::value& args) { }; auto find_response = [this](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, find_response"); Instance::PostMessage(&this->instance_, response->serialize().c_str()); }; @@ -827,7 +835,7 @@ void ApplicationManager::FindAppControl(const picojson::value& args) { } void ApplicationManager::GetAppsContext(const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); int callback_id = -1; const auto& callback = args.get(kCallbackId); @@ -885,7 +893,7 @@ void ApplicationManager::GetAppsContext(const picojson::value& args) { } void ApplicationManager::GetAppContext(const picojson::value& args, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); pid_t pid = 0; const auto& context_id = args.get("contextId"); @@ -934,7 +942,7 @@ void ApplicationManager::GetAppContext(const picojson::value& args, picojson::ob } void ApplicationManager::GetAppsInfo(const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); int callback_id = -1; const auto& callback = args.get(kCallbackId); @@ -943,6 +951,7 @@ void ApplicationManager::GetAppsInfo(const picojson::value& args) { } auto get_apps_info = [](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get_apps_info"); picojson::object& response_obj = response->get(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); @@ -951,6 +960,7 @@ void ApplicationManager::GetAppsInfo(const picojson::value& args) { .first->second.get(); auto app_info_cb = [](pkgmgrinfo_appinfo_h handle, void* user_data) -> int { + ScopeLogger("Entered into asynchronous function, app_info_cb"); if (nullptr == user_data) { return -1; } @@ -976,6 +986,7 @@ void ApplicationManager::GetAppsInfo(const picojson::value& args) { auto get_apps_info_response = [this, callback_id](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get_apps_info_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair(kCallbackId, picojson::value(static_cast(callback_id)))); Instance::PostMessage(&this->instance_, response->serialize().c_str()); @@ -987,7 +998,7 @@ void ApplicationManager::GetAppsInfo(const picojson::value& args) { } void ApplicationManager::GetAppInfo(const std::string& app_id, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); pkgmgrinfo_appinfo_h handle = nullptr; @@ -1004,7 +1015,7 @@ void ApplicationManager::GetAppInfo(const std::string& app_id, picojson::object* } char* ApplicationManager::GetPackageId(const std::string& app_id) { - LoggerD("Entered"); + ScopeLogger(); app_info_h handle; char* pkg_id = nullptr; @@ -1029,7 +1040,7 @@ char* ApplicationManager::GetPackageId(const std::string& app_id) { } void ApplicationManager::GetAppCerts(const std::string& app_id, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); char* package_id = nullptr; @@ -1115,7 +1126,7 @@ void ApplicationManager::GetAppCerts(const std::string& app_id, picojson::object } void ApplicationManager::GetAppSharedUri(const std::string& app_id, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); char* package_id = nullptr; @@ -1156,7 +1167,7 @@ void ApplicationManager::GetAppSharedUri(const std::string& app_id, picojson::ob } void ApplicationManager::GetAppMetaData(const std::string& app_id, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); pkgmgrinfo_appinfo_h handle = nullptr; @@ -1210,7 +1221,7 @@ class ApplicationListChangedBroker { static int ClientStatusListener(unsigned int target_uid, int id, const char* type, const char* package, const char* key, const char* val, const void* msg, void* data) { - LoggerD("Entered"); + ScopeLogger(); ApplicationListChangedBroker* that = static_cast(data); if (0 == strcasecmp(key, kStartKey)) { @@ -1226,7 +1237,7 @@ class ApplicationListChangedBroker { static int AppUninstallListener(uid_t target_uid, int id, const char* type, const char* package, const char* key, const char* val, const void* msg, void* data) { - LoggerD("Entered"); + ScopeLogger(); ApplicationListChangedBroker* that = static_cast(data); @@ -1244,12 +1255,12 @@ class ApplicationListChangedBroker { } void AddApplicationInstance(ApplicationInstance* app_instance) { - LoggerD("Entered"); + ScopeLogger(); app_instance_list_.push_back(app_instance); } void RemoveApplicationInstance(ApplicationInstance* app_instance) { - LoggerD("Entered"); + ScopeLogger(); for (auto it = app_instance_list_.begin(); it != app_instance_list_.end(); it++) { if (*it == app_instance) { app_instance_list_.erase(it); @@ -1260,13 +1271,13 @@ class ApplicationListChangedBroker { private: void HandleStart(const char* event_type, const char* package) { - LoggerD("Entered"); + ScopeLogger(); app_list_.clear(); set_event_type(event_type); } void HandleEnd(const char* package) { - LoggerD("Entered"); + ScopeLogger(); if (Event::kUninstalled == event_type_) { return; @@ -1319,7 +1330,7 @@ class ApplicationListChangedBroker { } void GetApplicationIdsFromPackage(const char* package) { - LoggerD("Entered"); + ScopeLogger(); package_info_h package_info = nullptr; int ret = package_info_create(package, &package_info); @@ -1341,7 +1352,7 @@ class ApplicationListChangedBroker { } void set_event_type(const char* type) { - LoggerD("Entered"); + ScopeLogger(); if (0 == strcasecmp(type, kInstallEvent)) { event_type_ = Event::kInstalled; } else if (0 == strcasecmp(type, kUpdateEvent)) { @@ -1353,7 +1364,7 @@ class ApplicationListChangedBroker { static bool ApplicationIdCallback(package_info_app_component_type_e comp_type, const char* app_id, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); if (nullptr != app_id) { static_cast(user_data)->app_list_.push_back(app_id); } @@ -1361,20 +1372,20 @@ class ApplicationListChangedBroker { } void HandleUninstallStart() { - LoggerD("Entered"); + ScopeLogger(); app_list_.clear(); set_event_type(kUninstallEvent); } void AddUninstalledAppId(const char* app_id) { - LoggerD("Entered"); + ScopeLogger(); if (nullptr != app_id) { app_list_.push_back(app_id); } } void HandleUninstallEnd() { - LoggerD("Entered"); + ScopeLogger(); for (auto& app_id : app_list_) { picojson::value value = picojson::value(picojson::object()); picojson::object& data_obj = value.get(); @@ -1398,7 +1409,7 @@ class ApplicationListChangedBroker { static ApplicationListChangedBroker g_application_list_changed_broker; void ApplicationManager::StartAppInfoEventListener(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); if (nullptr == pkgmgr_client_handle_ || nullptr == pkgmgr_client_uninstall_handle_) { if (nullptr == pkgmgr_client_handle_) { @@ -1444,7 +1455,7 @@ void ApplicationManager::StartAppInfoEventListener(picojson::object* out) { } void ApplicationManager::StopAppInfoEventListener() { - LoggerD("Entered"); + ScopeLogger(); if (nullptr != pkgmgr_client_handle_ || nullptr != pkgmgr_client_uninstall_handle_) { if (nullptr != pkgmgr_client_handle_) { @@ -1463,7 +1474,7 @@ void ApplicationManager::StopAppInfoEventListener() { void ApplicationManager::GetApplicationInformationSize(const picojson::value& args, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& package_id = args.get("packageId"); if (!package_id.is()) { @@ -1500,7 +1511,7 @@ void ApplicationManager::GetApplicationInformationSize(const picojson::value& ar void ApplicationManager::BroadcastEventHelper(const picojson::value& args, picojson::object& out, bool trusted) { - LoggerD("Entered"); + ScopeLogger(); int ret; std::string event_str = args.get("name").get(); @@ -1534,8 +1545,7 @@ void ApplicationManager::BroadcastEventHelper(const picojson::value& args, picoj } void ApplicationManager::OnEvent(const char* event_name, bundle* event_data, void* user_data) { - LoggerD("Entered"); - LOGGER(DEBUG) << event_name; + ScopeLogger("Event name is: '%f'", event_name); ApplicationManager* manager = static_cast(user_data); @@ -1592,7 +1602,7 @@ void ApplicationManager::OnEvent(const char* event_name, bundle* event_data, voi PlatformResult ApplicationManager::StartEventListener(const std::string& event_name, const JsonCallback& callback) { - LoggerD("Entered"); + ScopeLogger(); int ret; event_handler_h event_handler; @@ -1615,7 +1625,7 @@ PlatformResult ApplicationManager::StartEventListener(const std::string& event_n } void ApplicationManager::StopEventListener(const std::string& event_name) { - LoggerD("Entered"); + ScopeLogger(); int ret; event_handler_h event_handler; diff --git a/src/application/application_utils.cc b/src/application/application_utils.cc index a41e697..596d292 100644 --- a/src/application/application_utils.cc +++ b/src/application/application_utils.cc @@ -30,7 +30,7 @@ namespace application { void ApplicationUtils::CreateApplicationInformation(const pkgmgrinfo_appinfo_h handle, picojson::object* app_info) { - LoggerD("Enter"); + ScopeLogger(); char* tmp_str = nullptr; int ret = 0; @@ -81,6 +81,7 @@ void ApplicationUtils::CreateApplicationInformation(const pkgmgrinfo_appinfo_h h ret = pkgmgrinfo_appinfo_foreach_category( handle, [](const char* category, void* user_data) -> int { + ScopeLogger("Entered into asynchronous function"); picojson::array* categories_array = static_cast(user_data); if ((nullptr != category) && (nullptr != categories_array)) { @@ -136,6 +137,7 @@ void ApplicationUtils::CreateApplicationInformation(const pkgmgrinfo_appinfo_h h bool ApplicationUtils::CreateApplicationContext(const app_context_h handle, picojson::object* app_context) { + ScopeLogger(); char* app_id = nullptr; int ret = app_context_get_app_id(handle, &app_id); @@ -162,28 +164,28 @@ bool ApplicationUtils::CreateApplicationContext(const app_context_h handle, void ApplicationUtils::CreateApplicationContext(pid_t pid, const std::string& app_id, picojson::object* app_context) { - LoggerD("Enter"); + ScopeLogger(); app_context->insert(std::make_pair("id", picojson::value(std::to_string(pid)))); app_context->insert(std::make_pair("appId", picojson::value(app_id))); } void ApplicationUtils::CreateApplicationCertificate(const char* cert_type, const char* cert_value, picojson::object* app_certificate) { - LoggerD("Enter"); + ScopeLogger(); app_certificate->insert(std::make_pair("type", picojson::value(cert_type))); app_certificate->insert(std::make_pair("value", picojson::value(cert_value))); } void ApplicationUtils::CreateApplicationMetaData(const char* key, const char* value, picojson::object* app_meta_data) { - LoggerD("Enter"); + ScopeLogger(); app_meta_data->insert(std::make_pair("key", picojson::value(key))); app_meta_data->insert(std::make_pair("value", picojson::value(value))); } PlatformResult ApplicationUtils::ApplicationControlToService( const picojson::object& app_control_obj, app_control_h* app_control) { - LoggerD("Enter"); + ScopeLogger(); const auto it_operation = app_control_obj.find("operation"); const auto it_uri = app_control_obj.find("uri"); const auto it_mime = app_control_obj.find("mime"); @@ -248,7 +250,7 @@ PlatformResult ApplicationUtils::ApplicationControlToService( PlatformResult ApplicationUtils::ApplicationControlDataToServiceExtraData( const picojson::object& app_control_data, app_control_h app_control) { - LoggerD("Enter"); + ScopeLogger(); const auto it_key = app_control_data.find("key"); const auto it_value = app_control_data.find("value"); @@ -283,7 +285,7 @@ PlatformResult ApplicationUtils::ApplicationControlDataToServiceExtraData( void ApplicationUtils::ServiceToApplicationControl(app_control_h app_control, picojson::object* app_control_obj) { - LoggerD("Enter"); + ScopeLogger(); int ret = 0; char* tmp_str = nullptr; @@ -333,7 +335,7 @@ void ApplicationUtils::ServiceToApplicationControl(app_control_h app_control, void ApplicationUtils::ServiceExtraDataToApplicationControlData( app_control_h app_control, const std::string& key, picojson::object* app_control_data) { - LoggerD("Enter"); + ScopeLogger(); int ret = 0; bool is_array = false; @@ -384,12 +386,14 @@ void ApplicationUtils::ServiceExtraDataToApplicationControlData( bool ApplicationUtils::ServiceToApplicationControlDataArray(app_control_h app_control, picojson::array* data) { + ScopeLogger(); int ret = app_control_foreach_extra_data(app_control, ServiceExtraDataCallback, data); return APP_CONTROL_ERROR_NONE == ret; } bool ApplicationUtils::ServiceExtraDataCallback(app_control_h app_control, const char* key, void* user_data) { + ScopeLogger(); picojson::array* data = static_cast(user_data); data->push_back(picojson::value(picojson::object())); diff --git a/src/application/requested_application_control.cc b/src/application/requested_application_control.cc index 1c24f1a..d0a8661 100644 --- a/src/application/requested_application_control.cc +++ b/src/application/requested_application_control.cc @@ -33,7 +33,7 @@ namespace extension { namespace application { PlatformResult RequestedApplicationControl::set_bundle(const std::string& encoded_bundle) { - LoggerD("Entered"); + ScopeLogger(); if (encoded_bundle != bundle_) { bundle_ = encoded_bundle; @@ -56,7 +56,7 @@ PlatformResult RequestedApplicationControl::set_bundle(const std::string& encode } void RequestedApplicationControl::set_app_control(app_control_h app_control) { - LoggerD("Entered"); + ScopeLogger(); app_control_.reset(app_control, app_control_destroy); @@ -75,7 +75,7 @@ void RequestedApplicationControl::set_app_control(app_control_h app_control) { } void RequestedApplicationControl::ToJson(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); if (app_control_) { out->insert(std::make_pair("callerAppId", picojson::value(caller_app_id_))); @@ -87,7 +87,7 @@ void RequestedApplicationControl::ToJson(picojson::object* out) { } void RequestedApplicationControl::ReplyResult(const picojson::value& args, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& data_arr = args.get("data"); if (!data_arr.is()) { @@ -139,7 +139,7 @@ void RequestedApplicationControl::ReplyResult(const picojson::value& args, picoj } void RequestedApplicationControl::ReplyFailure(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); // read input data const std::string& encoded_bundle = GetEncodedBundle(); @@ -169,7 +169,7 @@ void RequestedApplicationControl::ReplyFailure(picojson::object* out) { } std::string RequestedApplicationControl::GetEncodedBundle() { - LoggerD("Entered"); + ScopeLogger(); std::string result; std::size_t size = 512; @@ -185,7 +185,7 @@ std::string RequestedApplicationControl::GetEncodedBundle() { } PlatformResult RequestedApplicationControl::VerifyCallerPresence() { - LoggerD("Entered"); + ScopeLogger(); if (caller_app_id_.empty()) { return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Cannot find caller.", diff --git a/src/archive/archive_callback_data.cc b/src/archive/archive_callback_data.cc index 450d9c0..10e1c8b 100644 --- a/src/archive/archive_callback_data.cc +++ b/src/archive/archive_callback_data.cc @@ -47,18 +47,18 @@ OperationCallbackData::OperationCallbackData(ArchiveCallbackType callback_type, m_is_error(false), m_is_canceled(false), m_err_code(ErrorCode::NO_ERROR) { - LoggerD("Entered"); + ScopeLogger(); } OperationCallbackData::~OperationCallbackData() { - LoggerD("Entered"); + ScopeLogger(); if (m_op_id > -1) { ArchiveManager::getInstance().eraseElementFromArchiveFileMap(m_op_id); } } void OperationCallbackData::setError(const ErrorCode& err_code, const std::string& err_message) { - LoggerD("Entered"); + ScopeLogger("Setting error, code is: [%d]", err_code); // store only first error if (!m_is_error) { m_err_code = err_code; @@ -68,77 +68,63 @@ void OperationCallbackData::setError(const ErrorCode& err_code, const std::strin } bool OperationCallbackData::isError() const { - LoggerD("Entered"); return m_is_error; } bool OperationCallbackData::isCanceled() const { - LoggerD("Enter"); return m_is_canceled; } void OperationCallbackData::setOperationId(long op_id) { - LoggerD("Entered"); m_op_id = op_id; } long OperationCallbackData::getOperationId() const { - LoggerD("Entered"); return m_op_id; } void OperationCallbackData::setCallbackId(double cid) { - LoggerD("Enter"); m_cid = cid; } double OperationCallbackData::getCallbackId() const { - LoggerD("Enter"); return m_cid; } void OperationCallbackData::setHandle(long handle) { - LoggerD("Enter"); m_handle = handle; } long OperationCallbackData::getHandle() const { - LoggerD("Enter"); return m_handle; } void OperationCallbackData::setIsCanceled(bool canceled) { - LoggerD("Enter"); m_is_canceled = canceled; } void OperationCallbackData::PostMessage(const char* msg) { - LoggerD("Enter"); + ScopeLogger(); Instance::PostMessage(&instance_, msg); } const ErrorCode& OperationCallbackData::getErrorCode() const { - LoggerD("Entered"); return m_err_code; } const std::string& OperationCallbackData::getErrorMessage() const { - LoggerD("Entered"); return m_err_message; } ArchiveCallbackType OperationCallbackData::getCallbackType() const { - LoggerD("Entered"); return m_callback_type; } ArchiveFilePtr OperationCallbackData::getArchiveFile() const { - LoggerD("Enter"); return m_caller_instance; } void OperationCallbackData::setArchiveFile(ArchiveFilePtr caller) { - LoggerD("Enter"); m_caller_instance = caller; } @@ -148,15 +134,15 @@ void OperationCallbackData::setArchiveFile(ArchiveFilePtr caller) { OpenCallbackData::OpenCallbackData(ArchiveInstance& instance) : OperationCallbackData(OPEN_CALLBACK_DATA, instance) { - LoggerD("Entered"); + ScopeLogger(); } OpenCallbackData::~OpenCallbackData() { - LoggerD("Entered"); + ScopeLogger(); } PlatformResult OpenCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) { - LoggerE("Entered"); + ScopeLogger(); filesystem::FilePtr file = archive_file_ptr->getFile(); if (!file) { @@ -212,25 +198,23 @@ PlatformResult OpenCallbackData::executeOperation(ArchiveFilePtr archive_file_pt GetEntriesCallbackData::GetEntriesCallbackData(ArchiveInstance& instance) : OperationCallbackData(GET_ENTRIES_CALLBACK_DATA, instance) { - LoggerD("Entered"); + ScopeLogger(); } GetEntriesCallbackData::~GetEntriesCallbackData() { - LoggerD("Entered"); + ScopeLogger(); } ArchiveFileEntryPtrMapPtr GetEntriesCallbackData::getEntries() const { - LoggerD("Entered"); return m_entries; } void GetEntriesCallbackData::setEntries(ArchiveFileEntryPtrMapPtr entries) { - LoggerD("Entered"); m_entries = entries; } PlatformResult GetEntriesCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) { - LoggerD("Entered"); + ScopeLogger(); setEntries(archive_file_ptr->getEntryMap()); @@ -247,35 +231,32 @@ PlatformResult GetEntriesCallbackData::executeOperation(ArchiveFilePtr archive_f GetEntryByNameCallbackData::GetEntryByNameCallbackData(ArchiveInstance& instance) : OperationCallbackData(GET_ENTRY_BY_NAME_CALLBACK_DATA, instance) { - LoggerD("Entered"); + ScopeLogger(); } GetEntryByNameCallbackData::~GetEntryByNameCallbackData() { - LoggerD("Entered"); + ScopeLogger(); } const std::string& GetEntryByNameCallbackData::getName() const { - LoggerD("Entered"); return m_name; } void GetEntryByNameCallbackData::setName(const std::string& name) { - LoggerD("Entered"); m_name = name; } ArchiveFileEntryPtr GetEntryByNameCallbackData::getFileEntry() const { - LoggerD("Entered"); + ScopeLogger(); return m_file_entry; } void GetEntryByNameCallbackData::setFileEntry(ArchiveFileEntryPtr entry) { - LoggerD("Entered"); m_file_entry = entry; } PlatformResult GetEntryByNameCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) { - LoggerD("Entered"); + ScopeLogger(); ArchiveFileEntryPtrMapPtr entries = archive_file_ptr->getEntryMap(); auto it = entries->find(getName()); @@ -310,20 +291,18 @@ PlatformResult GetEntryByNameCallbackData::executeOperation(ArchiveFilePtr archi BaseProgressCallback::BaseProgressCallback(ArchiveCallbackType callback_type, ArchiveInstance& instance) : OperationCallbackData(callback_type, instance), m_overwrite(false) { - LoggerD("Entered"); + ScopeLogger(); } BaseProgressCallback::~BaseProgressCallback() { - LoggerD("Entered"); + ScopeLogger(); } bool BaseProgressCallback::getOverwrite() const { - LoggerD("Entered"); return m_overwrite; } void BaseProgressCallback::setOverwrite(bool overwrite) { - LoggerD("Entered"); m_overwrite = overwrite; } @@ -336,7 +315,7 @@ struct ProgressHolder { }; void BaseProgressCallback::callSuccessCallbackOnMainThread() { - LoggerD("Entered"); + ScopeLogger(); guint id = g_idle_add(BaseProgressCallback::callSuccessCallbackCB, static_cast(this)); if (!id) { @@ -345,7 +324,7 @@ void BaseProgressCallback::callSuccessCallbackOnMainThread() { } gboolean BaseProgressCallback::callSuccessCallbackCB(void* data) { - LoggerD("Entered"); + ScopeLogger(); BaseProgressCallback* callback = static_cast(data); if (!callback) { @@ -376,7 +355,7 @@ gboolean BaseProgressCallback::callSuccessCallbackCB(void* data) { void BaseProgressCallback::callProgressCallback(long operationId, double value, const std::string& filename, double callbackId) { - LoggerD("Entered"); + ScopeLogger(); picojson::value val = picojson::value(picojson::object()); picojson::object& obj = val.get(); @@ -397,7 +376,7 @@ void BaseProgressCallback::callProgressCallback(long operationId, double value, void BaseProgressCallback::callProgressCallbackOnMainThread(const double progress, ArchiveFileEntryPtr current_entry) { - LoggerD("Entered"); + ScopeLogger(); ProgressHolder* ph = new (std::nothrow) ProgressHolder(); @@ -418,7 +397,7 @@ void BaseProgressCallback::callProgressCallbackOnMainThread(const double progres } gboolean BaseProgressCallback::callProgressCallbackCB(void* data) { - LoggerD("Entered"); + ScopeLogger(); ProgressHolder* ph = static_cast(data); if (!ph) { @@ -446,25 +425,23 @@ gboolean BaseProgressCallback::callProgressCallbackCB(void* data) { AddProgressCallback::AddProgressCallback(ArchiveInstance& instance) : BaseProgressCallback(ADD_PROGRESS_CALLBACK, instance) { - LoggerD("Entered"); + ScopeLogger(); } AddProgressCallback::~AddProgressCallback() { - LoggerD("Entered"); + ScopeLogger(); } ArchiveFileEntryPtr AddProgressCallback::getFileEntry() const { - LoggerD("Entered"); return m_file_entry; } void AddProgressCallback::setFileEntry(ArchiveFileEntryPtr file_entry) { - LoggerD("Entered"); m_file_entry = file_entry; } void AddProgressCallback::setBasePath(const std::string& path) { - LoggerD("Entered"); + ScopeLogger(); m_base_path = path; m_base_virt_path = common::FilesystemProvider::Create().GetVirtualPath(m_base_path); std::string::size_type pos = m_base_virt_path.find(filesystem::Path::getSeparator()); @@ -476,17 +453,15 @@ void AddProgressCallback::setBasePath(const std::string& path) { } const std::string& AddProgressCallback::getBasePath() { - LoggerD("Entered"); return m_base_path; } const std::string& AddProgressCallback::getBaseVirtualPath() { - LoggerD("Entered"); return m_base_virt_path; } PlatformResult AddProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) { - LoggerD("Entered"); + ScopeLogger(); if (!m_file_entry) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file to archive", @@ -544,39 +519,35 @@ ExtractAllProgressCallback::ExtractAllProgressCallback(ArchiveInstance& instance m_files_extracted(0), m_progress_overall(0), m_overall_decompressed(0) { - LoggerD("Entered"); + ScopeLogger(); } ExtractAllProgressCallback::~ExtractAllProgressCallback() { - LoggerD("Entered"); + ScopeLogger(); } filesystem::FilePtr ExtractAllProgressCallback::getDirectory() const { - LoggerD("Entered"); return m_directory; } void ExtractAllProgressCallback::setDirectory(filesystem::FilePtr directory) { - LoggerD("Entered"); m_directory = directory; } void ExtractAllProgressCallback::startedExtractingFile(unsigned long current_file_size) { - LoggerD("Entered"); - m_current_file_size = current_file_size; m_current_file_extracted_bytes = 0; } void ExtractAllProgressCallback::extractedPartOfFile(unsigned long bytes_decompressed) { - LoggerD("Entered"); + ScopeLogger(); m_current_file_extracted_bytes += bytes_decompressed; updateOverallProgress(bytes_decompressed); } void ExtractAllProgressCallback::finishedExtractingFile() { - LoggerD("Entered"); + ScopeLogger(); m_current_file_size = 0; m_current_file_extracted_bytes = 0; @@ -585,7 +556,7 @@ void ExtractAllProgressCallback::finishedExtractingFile() { } void ExtractAllProgressCallback::updateOverallProgress(unsigned long bytes_decompressed) { - LoggerD("Entered"); + ScopeLogger(); m_overall_decompressed += bytes_decompressed; m_progress_overall = static_cast(m_overall_decompressed + m_files_extracted) / @@ -597,7 +568,7 @@ void ExtractAllProgressCallback::updateOverallProgress(unsigned long bytes_decom } double ExtractAllProgressCallback::getCurrentFileProgress() const { - LoggerD("Entered"); + ScopeLogger(); if (m_current_file_size > 0) { return static_cast(m_current_file_extracted_bytes) / @@ -608,37 +579,26 @@ double ExtractAllProgressCallback::getCurrentFileProgress() const { } double ExtractAllProgressCallback::getOverallProgress() const { - LoggerD("Entered"); - return m_progress_overall; } PlatformResult ExtractAllProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) { - LoggerD("Entered"); return archive_file_ptr->extractAllTask(this); } void ExtractAllProgressCallback::setExpectedDecompressedSize(unsigned long exp_dec_size) { - LoggerD("Entered"); - m_expected_decompressed_size = exp_dec_size; } unsigned long ExtractAllProgressCallback::getExpectedDecompressedSize() const { - LoggerD("Entered"); - return m_expected_decompressed_size; } void ExtractAllProgressCallback::setNumberOfFilesToExtract(unsigned long files_count) { - LoggerD("Entered"); - m_files_to_extract = files_count; } unsigned long ExtractAllProgressCallback::getNumberOfFilesToExtract() const { - LoggerD("Entered"); - return m_files_to_extract; } @@ -649,7 +609,7 @@ unsigned long ExtractAllProgressCallback::getNumberOfFilesToExtract() const { const char* OPERATION_CANCELED_EXCEPTION = "OperationCanceledException"; OperationCanceledException::OperationCanceledException(const char* message) { - LoggerD("Entered"); + ScopeLogger(); } //---------------------------------------------------------------------------------------- @@ -658,46 +618,40 @@ OperationCanceledException::OperationCanceledException(const char* message) { ExtractEntryProgressCallback::ExtractEntryProgressCallback(ArchiveInstance& instance) : ExtractAllProgressCallback(instance), m_strip_name(false) { - LoggerD("Entered"); + ScopeLogger(); m_callback_type = EXTRACT_ENTRY_PROGRESS_CALLBACK; } ExtractEntryProgressCallback::~ExtractEntryProgressCallback() { - LoggerD("Entered"); + ScopeLogger(); } ArchiveFileEntryPtr ExtractEntryProgressCallback::getArchiveFileEntry() { - LoggerD("Entered"); return m_archive_file_entry; } void ExtractEntryProgressCallback::setArchiveFileEntry(ArchiveFileEntryPtr afentry) { - LoggerD("Entered"); m_archive_file_entry = afentry; } void ExtractEntryProgressCallback::setStripName(bool strip_name) { - LoggerD("Entered"); m_strip_name = strip_name; } bool ExtractEntryProgressCallback::getStripName() const { - LoggerD("Entered"); return m_strip_name; } void ExtractEntryProgressCallback::setStripBasePath(const std::string& strip_base_path) { - LoggerD("Entered"); m_strip_base_path = strip_base_path; } const std::string& ExtractEntryProgressCallback::getStripBasePath() const { - LoggerD("Entered"); return m_strip_base_path; } PlatformResult ExtractEntryProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) { - LoggerD("Entered"); + ScopeLogger(); if (!m_archive_file_entry) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", diff --git a/src/archive/archive_extension.cc b/src/archive/archive_extension.cc index dfa97a8..1e5b212 100644 --- a/src/archive/archive_extension.cc +++ b/src/archive/archive_extension.cc @@ -22,21 +22,21 @@ extern const char kSource_archive_api[]; common::Extension* CreateExtension() { - LoggerD("Enter"); + ScopeLogger(); return new ArchiveExtension; } ArchiveExtension::ArchiveExtension() { - LoggerD("Enter"); + ScopeLogger(); SetExtensionName("tizen.archive"); SetJavaScriptAPI(kSource_archive_api); } ArchiveExtension::~ArchiveExtension() { - LoggerD("Enter"); + ScopeLogger(); } common::Instance* ArchiveExtension::CreateInstance() { - LoggerD("Enter"); + ScopeLogger(); return new extension::archive::ArchiveInstance(); } diff --git a/src/archive/archive_file.cc b/src/archive/archive_file.cc index f52da91..797f963 100644 --- a/src/archive/archive_file.cc +++ b/src/archive/archive_file.cc @@ -34,7 +34,7 @@ namespace extension { namespace archive { Permission::Permission(bool r, bool w, bool rw, bool a) { - LoggerD("Enter"); + ScopeLogger(); permission[0] = r; permission[1] = w; permission[2] = rw; @@ -58,7 +58,7 @@ ArchiveFile::ArchiveFile() m_is_open(false), m_overwrite(false), m_created_as_new_empty_archive(false) { - LoggerD("Entered"); + ScopeLogger(); } ArchiveFile::ArchiveFile(FileMode file_mode) @@ -68,12 +68,12 @@ ArchiveFile::ArchiveFile(FileMode file_mode) m_is_open(false), m_overwrite(false), m_created_as_new_empty_archive(false) { - LoggerD("Enter"); + ScopeLogger(); m_file_mode = file_mode; } ArchiveFile::~ArchiveFile() { - LoggerD("Entered"); + ScopeLogger(); if (m_entry_map) { LoggerD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); @@ -86,7 +86,7 @@ ArchiveFile::~ArchiveFile() { } gboolean ArchiveFile::openTaskCompleteCB(void* data) { - LoggerD("Entered"); + ScopeLogger(); auto callback = static_cast(data); if (!callback) { @@ -136,7 +136,7 @@ gboolean ArchiveFile::openTaskCompleteCB(void* data) { } gboolean ArchiveFile::callErrorCallback(void* data) { - LoggerD("Entered"); + ScopeLogger(); auto callback = static_cast(data); if (!callback) { @@ -166,7 +166,7 @@ gboolean ArchiveFile::callErrorCallback(void* data) { } void ArchiveFile::taskManagerThread(gpointer data, gpointer user_data) { - LoggerD("Entered"); + ScopeLogger(); ArchiveFileHolder* archive_file_holder = static_cast(data); if (!archive_file_holder) { LoggerE("archive_file_holder is null"); @@ -227,7 +227,7 @@ void ArchiveFile::taskManagerThread(gpointer data, gpointer user_data) { } PlatformResult ArchiveFile::addOperation(OperationCallbackData* callback) { - LoggerD("Entered callback type:%d", callback->getCallbackType()); + ScopeLogger("callback type: %d", (int)callback->getCallbackType()); const long operation_id = callback->getOperationId(); callback->setArchiveFile(shared_from_this()); @@ -257,7 +257,7 @@ PlatformResult ArchiveFile::addOperation(OperationCallbackData* callback) { } PlatformResult ArchiveFile::extractAllTask(ExtractAllProgressCallback* callback) { - LoggerD("Enter"); + ScopeLogger(); filesystem::FilePtr directory = callback->getDirectory(); if (!directory) { @@ -309,7 +309,7 @@ PlatformResult ArchiveFile::extractAllTask(ExtractAllProgressCallback* callback) } PlatformResult ArchiveFile::getEntries(GetEntriesCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get list of files in archive", ("callback is NULL")); @@ -324,7 +324,7 @@ PlatformResult ArchiveFile::getEntries(GetEntriesCallbackData* callback) { } gboolean ArchiveFile::getEntriesTaskCompleteCB(void* data) { - LoggerD("Entered"); + ScopeLogger(); LoggerW("STUB Not calling success/error callback"); auto callback = static_cast(data); @@ -375,7 +375,7 @@ gboolean ArchiveFile::getEntriesTaskCompleteCB(void* data) { } PlatformResult ArchiveFile::extractAll(ExtractAllProgressCallback* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract all files from archive", ("callback is NULL")); @@ -390,7 +390,7 @@ PlatformResult ArchiveFile::extractAll(ExtractAllProgressCallback* callback) { } PlatformResult ArchiveFile::extractEntryTo(ExtractEntryProgressCallback* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", ("callback is NULL")); @@ -409,7 +409,7 @@ PlatformResult ArchiveFile::extractEntryTo(ExtractEntryProgressCallback* callbac } PlatformResult ArchiveFile::add(AddProgressCallback* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file to archive", ("callback is NULL")); @@ -428,7 +428,7 @@ PlatformResult ArchiveFile::add(AddProgressCallback* callback) { } void ArchiveFile::close() { - LoggerD("Entered"); + ScopeLogger(); if (!m_is_open) { LoggerD("Archive already closed"); @@ -439,7 +439,7 @@ void ArchiveFile::close() { } PlatformResult ArchiveFile::getEntryByName(GetEntryByNameCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get archive file entries by name", ("callback is NULL")); @@ -454,7 +454,7 @@ PlatformResult ArchiveFile::getEntryByName(GetEntryByNameCallbackData* callback) } gboolean ArchiveFile::getEntryByNameTaskCompleteCB(void* data) { - LoggerD("Entered"); + ScopeLogger(); auto callback = static_cast(data); if (!callback) { @@ -497,12 +497,10 @@ gboolean ArchiveFile::getEntryByNameTaskCompleteCB(void* data) { } filesystem::FilePtr ArchiveFile::getFile() const { - LoggerD("Entered"); return m_file; } void ArchiveFile::setFile(filesystem::FilePtr file) { - LoggerD("Entered"); m_file = file; } @@ -511,37 +509,31 @@ bool ArchiveFile::isOverwrite() const { } void ArchiveFile::setOverwrite(bool overwrite) { - LoggerD("Entered"); m_overwrite = overwrite; } unsigned long ArchiveFile::getDecompressedSize() const { - LoggerD("Entered"); return m_decompressed_size; } void ArchiveFile::setDecompressedSize(unsigned long decompressed_size) { - LoggerD("Entered"); m_decompressed_size = decompressed_size; } bool ArchiveFile::isOpen() const { - LoggerD("Entered"); return m_is_open; } void ArchiveFile::setIsOpen(bool is_open) { - LoggerD("Entered"); m_is_open = is_open; } ArchiveFileEntryPtrMapPtr ArchiveFile::getEntryMap() const { - LoggerD("Entered"); return m_entry_map; } void ArchiveFile::setEntryMap(ArchiveFileEntryPtrMapPtr entries) { - LoggerD("Entered"); + ScopeLogger(); if (m_entry_map) { LoggerD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); @@ -564,7 +556,7 @@ void ArchiveFile::setEntryMap(ArchiveFileEntryPtrMapPtr entries) { } PlatformResult ArchiveFile::createUnZipObject(UnZipPtr* unzip) { - LoggerD("Entered"); + ScopeLogger(); if (!m_is_open) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is not opened"); } @@ -582,7 +574,7 @@ PlatformResult ArchiveFile::createUnZipObject(UnZipPtr* unzip) { } PlatformResult ArchiveFile::createZipObject(ZipPtr* zip) { - LoggerD("Entered"); + ScopeLogger(); if (!m_is_open) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "File is not opened"); } @@ -600,7 +592,7 @@ PlatformResult ArchiveFile::createZipObject(ZipPtr* zip) { } bool ArchiveFile::isAllowedOperation(const std::string& method_name) { - LoggerD("Entered"); + ScopeLogger(); PermissionMap::iterator it = s_permission_map.find(method_name); if (it != s_permission_map.end()) { return it->second.permission[m_file_mode]; @@ -609,27 +601,23 @@ bool ArchiveFile::isAllowedOperation(const std::string& method_name) { } FileMode ArchiveFile::getFileMode() const { - LoggerD("Entered"); return m_file_mode; } void ArchiveFile::setFileMode(FileMode file_mode) { - LoggerD("Entered"); m_file_mode = file_mode; } void ArchiveFile::setCreatedAsNewEmptyArchive(bool new_and_empty) { - LoggerD("Entered"); m_created_as_new_empty_archive = new_and_empty; } bool ArchiveFile::isCreatedAsNewEmptyArchive() const { - LoggerD("Entered"); return m_created_as_new_empty_archive; } PlatformResult ArchiveFile::updateListOfEntries() { - LoggerD("Entered"); + ScopeLogger(); // For explanation please see: // ArchiveFile.h m_created_as_new_empty_archive description // @@ -673,7 +661,7 @@ PlatformResult ArchiveFile::updateListOfEntries() { bool ArchiveFile::isEntryWithNameInArchive(const std::string& name_in_zip, bool* out_is_directory, std::string* out_matching_name) { - LoggerD("Enter"); + ScopeLogger(); if (!m_entry_map) { LoggerW("m_entry_map is NULL"); diff --git a/src/archive/archive_file_entry.cc b/src/archive/archive_file_entry.cc index d66a1c6..80b66f8 100644 --- a/src/archive/archive_file_entry.cc +++ b/src/archive/archive_file_entry.cc @@ -39,11 +39,11 @@ ArchiveFileEntry::ArchiveFileEntry(filesystem::FilePtr file) m_compressed_size(0), m_modified(0), m_compression_level(s_default_compression_level) { - LoggerD("Entered"); + ScopeLogger(); } ArchiveFileEntry::~ArchiveFileEntry() { - LoggerD("Entered"); + ScopeLogger(); } unsigned long ArchiveFileEntry::getCompressedSize() const { @@ -118,6 +118,7 @@ ArchiveFile* ArchiveFileEntry::getArchiveFileNonProtectPtr() { } PlatformResult ArchiveFileEntry::extractTo(ExtractEntryProgressCallback* callback) { + ScopeLogger(); if (!m_archive) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry", ("m_archive is NULL")); diff --git a/src/archive/archive_instance.cc b/src/archive/archive_instance.cc index 6c26eda..a4ebd8c 100644 --- a/src/archive/archive_instance.cc +++ b/src/archive/archive_instance.cc @@ -53,7 +53,7 @@ const std::string kBestCompressionStr = "BEST"; } // namespace ArchiveInstance::ArchiveInstance() { - LoggerD("Entered"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -79,11 +79,11 @@ ArchiveInstance::ArchiveInstance() { } ArchiveInstance::~ArchiveInstance() { - LoggerD("Entered"); + ScopeLogger(); } void ArchiveInstance::PostError(const PlatformResult& e, double callback_id) { - LoggerD("Entered"); + ScopeLogger(); LoggerE("Posting an error: %d, message: %s", e.error_code(), e.message().c_str()); @@ -97,8 +97,7 @@ void ArchiveInstance::PostError(const PlatformResult& e, double callback_id) { } void ArchiveInstance::Open(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); + ScopeLogger("%s", args.serialize().c_str()); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); @@ -230,8 +229,7 @@ void ArchiveInstance::Open(const picojson::value& args, picojson::object& out) { } void ArchiveInstance::Abort(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); + ScopeLogger("%s", args.serialize().c_str()); picojson::object data = args.get(); picojson::value v_op_id = data.at(PARAM_OPERATION_ID); @@ -244,7 +242,7 @@ void ArchiveInstance::Abort(const picojson::value& args, picojson::object& out) } unsigned int ConvertStringToCompressionLevel(const std::string& level) { - LoggerD("Entered"); + ScopeLogger(); if (kNoCompressionStr == level) { return Z_NO_COMPRESSION; @@ -258,8 +256,7 @@ unsigned int ConvertStringToCompressionLevel(const std::string& level) { } void ArchiveInstance::Add(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); + ScopeLogger("%s", args.serialize().c_str()); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); @@ -346,8 +343,7 @@ void ArchiveInstance::Add(const picojson::value& args, picojson::object& out) { } void ArchiveInstance::ExtractAll(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); + ScopeLogger("%s", args.serialize().c_str()); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); @@ -409,8 +405,7 @@ void ArchiveInstance::ExtractAll(const picojson::value& args, picojson::object& } void ArchiveInstance::GetEntries(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); + ScopeLogger("%s", args.serialize().c_str()); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); @@ -454,8 +449,7 @@ void ArchiveInstance::GetEntries(const picojson::value& args, picojson::object& } void ArchiveInstance::GetEntryByName(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); + ScopeLogger("%s", args.serialize().c_str()); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); @@ -501,8 +495,7 @@ void ArchiveInstance::GetEntryByName(const picojson::value& args, picojson::obje } void ArchiveInstance::Close(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); + ScopeLogger("%s", args.serialize().c_str()); picojson::object data = args.get(); picojson::value v_handle = data.at(ARCHIVE_FILE_HANDLE); @@ -523,8 +516,7 @@ void ArchiveInstance::Close(const picojson::value& args, picojson::object& out) } void ArchiveInstance::Extract(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); - LoggerD("%s", args.serialize().c_str()); + ScopeLogger("%s", args.serialize().c_str()); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); @@ -604,7 +596,7 @@ void ArchiveInstance::Extract(const picojson::value& args, picojson::object& out } void ArchiveInstance::FetchVirtualRoots(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); picojson::array roots; for (const auto& root : common::FilesystemProvider::Create().GetVirtualPaths()) { diff --git a/src/archive/archive_manager.cc b/src/archive/archive_manager.cc index 45f6335..bcee48f 100644 --- a/src/archive/archive_manager.cc +++ b/src/archive/archive_manager.cc @@ -25,20 +25,20 @@ namespace archive { using namespace filesystem; ArchiveManager::ArchiveManager() : m_next_unique_id(0) { - LoggerD("Initialize ArchiveManager"); + ScopeLogger("Initialize ArchiveManager"); // create thread pool with max threads = 1 to make API calls async but // only one call at time m_pool = g_thread_pool_new(ArchiveFile::taskManagerThread, NULL, 1, true, NULL); } ArchiveManager::~ArchiveManager() { - LoggerD("Deinitialize ArchiveManager"); + ScopeLogger("Deinitialize ArchiveManager"); // finish only current task and wait for thread to stop g_thread_pool_free(m_pool, true, true); } ArchiveManager& ArchiveManager::getInstance() { - LoggerD("Entered"); + ScopeLogger(); static ArchiveManager instance; return instance; } @@ -48,7 +48,7 @@ GThreadPool* ArchiveManager::getThreadPool() { } void ArchiveManager::abort(long operation_id) { - LoggerD("Entered"); + ScopeLogger(); ArchiveFileMap::iterator it = m_archive_file_map.find(operation_id); if (it != m_archive_file_map.end()) { @@ -67,7 +67,7 @@ void ArchiveManager::abort(long operation_id) { } void ArchiveManager::erasePrivData(long handle) { - LoggerD("Entered"); + ScopeLogger(); ArchiveFileMap::iterator it = m_priv_map.find(handle); if (it != m_priv_map.end()) { @@ -76,7 +76,7 @@ void ArchiveManager::erasePrivData(long handle) { } long ArchiveManager::addPrivData(ArchiveFilePtr archive_file_ptr) { - LoggerD("Entered"); + ScopeLogger(); long handle = ++m_next_unique_id; m_priv_map.insert(ArchiveFilePair(handle, archive_file_ptr)); @@ -93,7 +93,7 @@ PlatformResult ArchiveManager::getPrivData(long handle, ArchiveFilePtr* archive_ } PlatformResult ArchiveManager::open(OpenCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); // ArchiveFilePtr a_ptr = callback->getArchiveFile(); // std::string filename = callback->getFile(); @@ -107,7 +107,7 @@ PlatformResult ArchiveManager::open(OpenCallbackData* callback) { } void ArchiveManager::eraseElementFromArchiveFileMap(long operation_id) { - LoggerD("Entered"); + ScopeLogger(); ArchiveFileMap::iterator it = m_archive_file_map.find(operation_id); if (it != m_archive_file_map.end()) { m_archive_file_map.erase(it); diff --git a/src/archive/archive_utils.cc b/src/archive/archive_utils.cc index 6976722..3c91f2b 100644 --- a/src/archive/archive_utils.cc +++ b/src/archive/archive_utils.cc @@ -27,7 +27,7 @@ namespace archive { using namespace filesystem; std::string bytesToReadableString(const size_t num_bytes) { - LoggerD("Enter"); + ScopeLogger(); std::stringstream ss; static const size_t one_mb = 1024 * 1024; static const size_t one_kb = 1024; @@ -45,7 +45,7 @@ std::string bytesToReadableString(const size_t num_bytes) { } PlatformResult fileModeToString(FileMode fm, std::string* fm_str) { - LoggerD("Enter"); + ScopeLogger(); switch (fm) { case FileMode::READ: *fm_str = "r"; @@ -66,7 +66,7 @@ PlatformResult fileModeToString(FileMode fm, std::string* fm_str) { } PlatformResult stringToFileMode(std::string fmString, FileMode* fm) { - LoggerD("Enter"); + ScopeLogger(); if (!fmString.compare("r")) { *fm = FileMode::READ; return PlatformResult(ErrorCode::NO_ERROR); @@ -87,7 +87,7 @@ PlatformResult stringToFileMode(std::string fmString, FileMode* fm) { void getBasePathAndName(const std::string& filepath, std::string& out_basepath, std::string& out_name) { - LoggerD("Enter"); + ScopeLogger(); const size_t filepath_len = filepath.length(); size_t name_end_index = filepath_len; @@ -114,7 +114,7 @@ void getBasePathAndName(const std::string& filepath, std::string& out_basepath, } std::string removeDuplicatedSlashesFromPath(const std::string& path) { - LoggerD("Enter"); + ScopeLogger(); const size_t path_len = path.length(); std::string out; @@ -138,7 +138,7 @@ std::string removeDuplicatedSlashesFromPath(const std::string& path) { } bool isDirectoryPath(const std::string& path) { - LoggerD("Enter"); + ScopeLogger(); if (path.empty()) { return false; } @@ -148,7 +148,7 @@ bool isDirectoryPath(const std::string& path) { } std::string removeTrailingDirectorySlashFromPath(const std::string& path) { - LoggerD("Enter"); + ScopeLogger(); if (!isDirectoryPath(path)) { return path; } @@ -157,7 +157,7 @@ std::string removeTrailingDirectorySlashFromPath(const std::string& path) { } std::string stripBasePathFromPath(const std::string& fullpath) { - LoggerD("Enter"); + ScopeLogger(); const size_t location = fullpath.find_last_of("/\\"); if (std::string::npos == location) { return fullpath; @@ -176,7 +176,7 @@ static std::string errCRC = "CRC error"; static std::string errUnknown = "Unknown error"; const std::string& getArchiveErrorMessage(int errorCode) { - LoggerD("Enter"); + ScopeLogger(); /** * All errors are defined in minizip library in files: * zip.h and unzip.h @@ -207,7 +207,7 @@ const std::string& getArchiveErrorMessage(int errorCode) { } std::string getBasePathFromPath(const std::string& fullpath) { - LoggerD("Enter"); + ScopeLogger(); const std::string tmp_path = removeTrailingDirectorySlashFromPath(fullpath); const size_t location = tmp_path.find_last_of("/\\"); if (std::string::npos == location) { @@ -218,7 +218,7 @@ std::string getBasePathFromPath(const std::string& fullpath) { } std::string getArchiveLogMessage(const int errorCode, const std::string& hint) { - LoggerD("Enter"); + ScopeLogger(); std::stringstream ss; ss << "Failed " << hint << " : " << getArchiveErrorMessage(errorCode) << ", " << errorCode; return std::string(ss.str()); diff --git a/src/archive/filesystem_file.cc b/src/archive/filesystem_file.cc index 9356a91..7a3fc47 100644 --- a/src/archive/filesystem_file.cc +++ b/src/archive/filesystem_file.cc @@ -24,12 +24,12 @@ namespace filesystem { File::File(NodePtr node, const File::PermissionList& parentPermissions, const std::string& original_location) : m_node(node), m_parentPerms(parentPermissions) { - LoggerD("original_location is fullPath: %s", original_location.c_str()); + ScopeLogger("original_location is fullPath: %s", original_location.c_str()); m_original_fullpath = original_location; } File::~File() { - LoggerD("Enter"); + ScopeLogger(); } NodePtr File::getNode() const { diff --git a/src/archive/filesystem_node.cc b/src/archive/filesystem_node.cc index 7454b18..b2908fd 100644 --- a/src/archive/filesystem_node.cc +++ b/src/archive/filesystem_node.cc @@ -39,7 +39,7 @@ using namespace common; #define MAX_NODE_LENGTH 256 PlatformResult Node::checkPermission(const PathPtr& path, const std::string& mode, NodeType type, bool* granted) { - LoggerD("Enter"); + ScopeLogger(); *granted = false; switch (type) { @@ -109,7 +109,7 @@ PlatformResult Node::checkPermission(const PathPtr& path, const std::string& mod } PlatformResult Node::resolve(const PathPtr& path, NodePtr* node) { - LoggerD("Entered path:[%s]", path->getFullPath().c_str()); + ScopeLogger("path: %s", path->getFullPath().c_str()); struct stat info; struct stat syminfo; @@ -163,7 +163,7 @@ PathPtr Node::getPath() const { } PlatformResult Node::getChild(const PathPtr& path, NodePtr* node) { - LoggerD("Enter"); + ScopeLogger(); if (m_type != NT_DIRECTORY) { return LogAndCreateResult(ErrorCode::IO_ERR, "Not a directory."); } @@ -183,7 +183,7 @@ void Node::setPermissions(int perms) { } PlatformResult Node::getChildNames(Node::NameList* out_name_list) const { - LoggerD("Enter"); + ScopeLogger(); if (m_type != NT_DIRECTORY) { return LogAndCreateResult(ErrorCode::IO_ERR, "Node is not directory."); } @@ -221,7 +221,7 @@ PlatformResult Node::getChildNames(Node::NameList* out_name_list) const { } PlatformResult Node::getChildNodes(NodeList* out_node_list) const { - LoggerD("Enter"); + ScopeLogger(); if (m_type != NT_DIRECTORY) { SLoggerE("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); @@ -270,7 +270,7 @@ PlatformResult Node::getChildNodes(NodeList* out_node_list) const { } PlatformResult Node::createChild(const PathPtr& path, NodeType type, NodePtr* node, int options) { - LoggerD("Enter"); + ScopeLogger(); if (m_type != NT_DIRECTORY) { return LogAndCreateResult(ErrorCode::IO_ERR, "Parent node is not a directory."); } @@ -315,7 +315,7 @@ PlatformResult Node::createChild(const PathPtr& path, NodeType type, NodePtr* no } PlatformResult Node::remove(int options) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult result(ErrorCode::NO_ERROR); switch (m_type) { case NT_FILE: @@ -331,7 +331,7 @@ PlatformResult Node::remove(int options) { } PlatformResult Node::getSize(unsigned long long* size) const { - LoggerD("Enter"); + ScopeLogger(); if (m_type == NT_DIRECTORY) { return LogAndCreateResult(ErrorCode::IO_ERR, "Getting size for directories is not supported."); } @@ -353,7 +353,7 @@ PlatformResult Node::getSize(unsigned long long* size) const { } PlatformResult Node::getCreated(std::time_t* time) const { - LoggerD("Enter"); + ScopeLogger(); struct stat info; PlatformResult result = stat(m_path, &info); if (result.error_code() != ErrorCode::NO_ERROR) { @@ -365,7 +365,7 @@ PlatformResult Node::getCreated(std::time_t* time) const { } PlatformResult Node::getModified(std::time_t* time) const { - LoggerD("Enter"); + ScopeLogger(); struct stat info; PlatformResult result = stat(m_path, &info); if (result.error_code() != ErrorCode::NO_ERROR) { @@ -377,7 +377,7 @@ PlatformResult Node::getModified(std::time_t* time) const { } PlatformResult Node::getParent(NodePtr* node) const { - LoggerD("Enter"); + ScopeLogger(); // LocationPaths roots = Manager::getInstance().getLocationPaths(); // for (LocationPaths::iterator it = roots.begin(); it != roots.end(); ++it) { @@ -394,7 +394,7 @@ PlatformResult Node::getParent(NodePtr* node) const { } PlatformResult Node::getMode(int* mode) const { - LoggerD("Enter"); + ScopeLogger(); struct stat info; PlatformResult result = stat(m_path, &info); @@ -432,7 +432,7 @@ PlatformResult Node::getMode(int* mode) const { } PlatformResult Node::exists(const PathPtr& path, bool* existed) { - LoggerD("Enter"); + ScopeLogger(); struct stat info; memset(&info, 0, sizeof(struct stat)); @@ -453,7 +453,7 @@ PlatformResult Node::exists(const PathPtr& path, bool* existed) { } PlatformResult Node::stat(const PathPtr& path, struct stat* out_info) { - LoggerD("Enter"); + ScopeLogger(); struct stat info; memset(&info, 0, sizeof(struct stat)); @@ -466,11 +466,11 @@ PlatformResult Node::stat(const PathPtr& path, struct stat* out_info) { } Node::Node(const PathPtr& path, NodeType type) : m_path(path), m_type(type), m_perms(PERM_NONE) { - LoggerD("Enter"); + ScopeLogger(); } PlatformResult Node::createAsFile(const PathPtr& path, NodePtr* node, int /* options */) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult result = createAsFileInternal(path); if (result.error_code() == ErrorCode::NO_ERROR) { @@ -480,7 +480,7 @@ PlatformResult Node::createAsFile(const PathPtr& path, NodePtr* node, int /* opt } PlatformResult Node::createAsFileInternal(const PathPtr& path) { - LoggerD("Enter"); + ScopeLogger(); FILE* file = std::fopen(path->getFullPath().c_str(), "wb"); if (!file) { @@ -492,7 +492,7 @@ PlatformResult Node::createAsFileInternal(const PathPtr& path) { } PlatformResult Node::createAsDirectory(const PathPtr& path, NodePtr* node, int options) { - LoggerD("Enter"); + ScopeLogger(); // if (options & OPT_RECURSIVE) { // auto parts = Utils::getParts(path); @@ -508,7 +508,7 @@ PlatformResult Node::createAsDirectory(const PathPtr& path, NodePtr* node, int o } PlatformResult Node::createAsDirectoryInternal(const PathPtr& path) { - LoggerD("Enter"); + ScopeLogger(); if (mkdir(path->getFullPath().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) { return LogAndCreateResult(ErrorCode::IO_ERR, "Platform node could not be created."); @@ -517,7 +517,7 @@ PlatformResult Node::createAsDirectoryInternal(const PathPtr& path) { } PlatformResult Node::removeAsFile(const PathPtr& path) { - LoggerD("Enter"); + ScopeLogger(); auto fullPath = path->getFullPath(); if (unlink(fullPath.c_str()) != 0) { @@ -528,7 +528,7 @@ PlatformResult Node::removeAsFile(const PathPtr& path) { } PlatformResult Node::removeAsDirectory(const PathPtr& path, bool recursive) { - LoggerD("Enter"); + ScopeLogger(); if (recursive) { DIR* dir = opendir(path->getFullPath().c_str()); @@ -574,7 +574,7 @@ PlatformResult Node::removeAsDirectory(const PathPtr& path, bool recursive) { } bool Node::isSubPath(std::string aDirPath, PathPtr aFilePath) { - LoggerD("Enter"); + ScopeLogger(); auto myPath = aDirPath; if (!myPath.empty() && myPath[myPath.length() - 1] != Path::getSeparator()) { myPath += Path::getSeparator(); diff --git a/src/archive/filesystem_path.cc b/src/archive/filesystem_path.cc index 8bf7ab4..5f1fa81 100644 --- a/src/archive/filesystem_path.cc +++ b/src/archive/filesystem_path.cc @@ -33,7 +33,7 @@ namespace filesystem { const Path::SeparatorType Path::m_pathSeparator = '/'; std::string Path::replaceVirtualRootPath(const char* path) { - LoggerD("Enter"); + ScopeLogger(); const char* old_path = "/opt/usr/media"; char replace_path[MAX_PATH_SIZE] = { @@ -51,7 +51,7 @@ std::string Path::replaceVirtualRootPath(const char* path) { } PathPtr Path::create(const std::string& path) { - LoggerD("Enter"); + ScopeLogger(); auto result = std::shared_ptr(new Path()); result->reset(replaceVirtualRootPath(path.c_str())); return result; @@ -96,10 +96,11 @@ PathPtr Path::clone() const { } Path::Path() { + ScopeLogger(); } void Path::reset(const std::string& str) { - LoggerD("Enter"); + ScopeLogger(); if (!isValid(str)) { LoggerD("Invalid string %s", str.c_str()); LoggerW("throw NotFoundException"); diff --git a/src/archive/un_zip.cc b/src/archive/un_zip.cc index de34b5f..cf2260a 100644 --- a/src/archive/un_zip.cc +++ b/src/archive/un_zip.cc @@ -44,12 +44,12 @@ UnZip::UnZip(const std::string& filename) m_unzip(NULL), m_default_buffer_size(1024 * 1024), m_is_open(false) { - LoggerD("Entered"); + ScopeLogger(); m_unzip = unzOpen(filename.c_str()); } UnZip::~UnZip() { - LoggerD("Enter"); + ScopeLogger(); for (auto& x : path_access_map) { LoggerD("Setting permission for path: %s [%d] ", x.first.c_str(), x.second); if (chmod(x.first.c_str(), x.second) == -1) { @@ -61,7 +61,7 @@ UnZip::~UnZip() { } PlatformResult UnZip::close() { - LoggerD("Entered"); + ScopeLogger(); if (!m_is_open) { LoggerD("Unzip already closed - exiting"); return PlatformResult(ErrorCode::NO_ERROR); @@ -79,7 +79,7 @@ PlatformResult UnZip::close() { } PlatformResult UnZip::open(const std::string& filename, UnZipPtr* out_unzip) { - LoggerD("Entered"); + ScopeLogger(); UnZipPtr unzip = UnZipPtr(new UnZip(filename)); if (!unzip->m_unzip) { @@ -93,7 +93,7 @@ PlatformResult UnZip::open(const std::string& filename, UnZipPtr* out_unzip) { PlatformResult UnZip::listEntries(unsigned long* decompressedSize, ArchiveFileEntryPtrMapPtr* out_map) { - LoggerD("Enter"); + ScopeLogger(); if (!m_is_open) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to get list of files in zip archive"); } @@ -169,7 +169,7 @@ PlatformResult UnZip::listEntries(unsigned long* decompressedSize, PlatformResult UnZip::extractAllFilesTo(const std::string& extract_path, ExtractAllProgressCallback* callback) { - LoggerD("Enter"); + ScopeLogger(); if (!m_is_open) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to extract zip archive"); } @@ -224,7 +224,7 @@ struct ExtractDataHolder { }; PlatformResult UnZip::extractTo(ExtractEntryProgressCallback* callback) { - LoggerD("Enter"); + ScopeLogger(); if (!m_is_open) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Extract archive file entry failed"); } @@ -295,7 +295,7 @@ PlatformResult UnZip::extractTo(ExtractEntryProgressCallback* callback) { PlatformResult UnZip::extractItFunction(const std::string& file_name, unz_file_info& file_info, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); ExtractDataHolder* h = static_cast(user_data); if (!h) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not list content of zip archive", @@ -315,7 +315,7 @@ PlatformResult UnZip::IterateFilesInZip(unz_global_info& gi, const std::string& OperationCallbackData* callback, UnZip::IterateFunction itfunc, unsigned int& num_file_or_folder_matched, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); int err = unzGoToFirstFile(m_unzip); if (UNZ_OK != err) { LoggerW("%s", getArchiveLogMessage(err, "unzGoToFirstFile()").c_str()); @@ -378,7 +378,7 @@ PlatformResult UnZip::IterateFilesInZip(unz_global_info& gi, const std::string& PlatformResult UnZip::extractCurrentFile(const std::string& extract_path, const std::string& base_strip_path, BaseProgressCallback* callback) { - LoggerD("Entered"); + ScopeLogger(); if (callback->isCanceled()) { return LogAndCreateResult(ErrorCode::OPERATION_CANCELED_ERR, "Operation canceled"); @@ -400,7 +400,7 @@ struct ArchiveStatistics { PlatformResult generateArchiveStatistics(const std::string& file_name, unz_file_info& file_info, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); if (user_data) { ArchiveStatistics* astats = static_cast(user_data); astats->uncompressed_size += file_info.uncompressed_size; @@ -417,7 +417,7 @@ PlatformResult generateArchiveStatistics(const std::string& file_name, unz_file_ PlatformResult UnZip::updateCallbackWithArchiveStatistics(ExtractAllProgressCallback* callback, unz_global_info& out_global_info, const std::string& optional_filter) { - LoggerD("Enter"); + ScopeLogger(); int err = unzGetGlobalInfo(m_unzip, &out_global_info); if (UNZ_OK != err) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, diff --git a/src/archive/un_zip_extract_request.cc b/src/archive/un_zip_extract_request.cc index e3b7adb..6996470 100644 --- a/src/archive/un_zip_extract_request.cc +++ b/src/archive/un_zip_extract_request.cc @@ -40,7 +40,7 @@ using namespace common; using common::tools::GetErrorString; FilePathStatus getPathStatus(const std::string& path) { - LoggerD("Enter"); + ScopeLogger(); if (path.empty()) { return FPS_NOT_EXIST; } @@ -60,7 +60,7 @@ FilePathStatus getPathStatus(const std::string& path) { void divideToPathAndName(const std::string& filepath, std::string& out_path, std::string& out_name) { - LoggerD("Enter"); + ScopeLogger(); size_t pos_last_dir = filepath.find_last_of("/\\"); if (pos_last_dir == std::string::npos) { out_path = ""; @@ -72,7 +72,7 @@ void divideToPathAndName(const std::string& filepath, std::string& out_path, } void createMissingDirectories(const std::string& path, bool check_first = true) { - LoggerD("Enter"); + ScopeLogger(); if (check_first) { const FilePathStatus path_status = getPathStatus(path); // LoggerD("[%s] status: %d", path.c_str(), path_status); @@ -103,7 +103,7 @@ void createMissingDirectories(const std::string& path, bool check_first = true) } void changeFileAccessAndModifyDate(const std::string& filepath, tm_unz tmu_date) { - LoggerD("Enter"); + ScopeLogger(); struct utimbuf ut; struct tm newdate; newdate.tm_sec = tmu_date.tm_sec; @@ -129,7 +129,7 @@ void changeFileAccessAndModifyDate(const std::string& filepath, tm_unz tmu_date) PlatformResult UnZipExtractRequest::execute(UnZip& owner, const std::string& extract_path, const std::string& base_strip_path, BaseProgressCallback* callback) { - LoggerD("Enter"); + ScopeLogger(); UnZipExtractRequest req(owner, extract_path, base_strip_path, callback); if (!req.m_callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Problem with callback functionality", @@ -156,12 +156,12 @@ UnZipExtractRequest::UnZipExtractRequest(UnZip& owner, const std::string& extrac m_new_dir_status(FPS_NOT_EXIST), m_is_directory_entry(false) { - LoggerD("Enter"); + ScopeLogger(); m_filename_inzip[0] = '\0'; } PlatformResult UnZipExtractRequest::run() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult result = getCurrentFileInfo(); if (result.error_code() != ErrorCode::NO_ERROR) { @@ -179,7 +179,7 @@ PlatformResult UnZipExtractRequest::run() { } UnZipExtractRequest::~UnZipExtractRequest() { - LoggerD("Enter"); + ScopeLogger(); if (m_output_file) { fclose(m_output_file); @@ -207,7 +207,7 @@ UnZipExtractRequest::~UnZipExtractRequest() { } PlatformResult UnZipExtractRequest::getCurrentFileInfo() { - LoggerD("Entered"); + ScopeLogger(); int err = unzGetCurrentFileInfo(m_owner.m_unzip, &m_file_info, m_filename_inzip, sizeof(m_filename_inzip), NULL, 0, NULL, 0); if (err != UNZ_OK) { @@ -270,7 +270,7 @@ PlatformResult UnZipExtractRequest::getCurrentFileInfo() { } PlatformResult UnZipExtractRequest::handleDirectoryEntry() { - LoggerD("Entered"); + ScopeLogger(); if (FPS_DIRECTORY != m_new_dir_status) { if (FPS_FILE == m_new_dir_status) { if (m_callback->getOverwrite()) { // Is a file & overwrite is set: @@ -312,7 +312,7 @@ PlatformResult UnZipExtractRequest::handleDirectoryEntry() { } PlatformResult UnZipExtractRequest::prepareOutputSubdirectory() { - LoggerD("Entered"); + ScopeLogger(); // This zip entry points to file - verify that parent directory in output dir exists if (FPS_DIRECTORY != m_new_dir_status) { if (FPS_FILE == m_new_dir_status) { @@ -362,7 +362,7 @@ PlatformResult UnZipExtractRequest::prepareOutputSubdirectory() { } PlatformResult UnZipExtractRequest::handleFileEntry() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult result = prepareOutputSubdirectory(); if (result.error_code() != ErrorCode::NO_ERROR) { diff --git a/src/archive/zip.cc b/src/archive/zip.cc index aefd6c9..b2fb1b4 100644 --- a/src/archive/zip.cc +++ b/src/archive/zip.cc @@ -35,7 +35,7 @@ namespace archive { using namespace common; void Zip::generateZipFileInfo(const std::string& filename, zip_fileinfo& out_zi) { - LoggerD("Enter"); + ScopeLogger(); memset(&out_zi, 0, sizeof(zip_fileinfo)); @@ -67,7 +67,7 @@ void Zip::generateZipFileInfo(const std::string& filename, zip_fileinfo& out_zi) Zip::Zip(const std::string& filename, ZipOpenMode open_mode) : m_zipfile_name(filename), m_zip(NULL), m_default_buffer_size(1024 * 1024), m_is_open(false) { - LoggerD("Entered"); + ScopeLogger(); int append_mode = APPEND_STATUS_CREATE; if (ZOM_CREATEAFTER == open_mode) { @@ -81,13 +81,13 @@ Zip::Zip(const std::string& filename, ZipOpenMode open_mode) } Zip::~Zip() { - LoggerD("Enter"); + ScopeLogger(); close(); } PlatformResult Zip::close() { - LoggerD("Entered"); + ScopeLogger(); if (!m_is_open) { LoggerD("Already closed - exiting."); return PlatformResult(ErrorCode::NO_ERROR); @@ -105,7 +105,7 @@ PlatformResult Zip::close() { } PlatformResult Zip::createNew(const std::string& filename, ZipPtr* out_zip) { - LoggerD("Entered"); + ScopeLogger(); ZipPtr zip = ZipPtr(new Zip(filename, ZOM_CREATE)); if (!zip->m_zip) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Opening/creating zip file failed", @@ -117,7 +117,7 @@ PlatformResult Zip::createNew(const std::string& filename, ZipPtr* out_zip) { } PlatformResult Zip::open(const std::string& filename, ZipPtr* out_zip) { - LoggerD("Entered"); + ScopeLogger(); ZipPtr zip = ZipPtr(new Zip(filename, ZOM_ADDINZIP)); if (!zip->m_zip) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Opening/creating zip file failed", @@ -129,7 +129,7 @@ PlatformResult Zip::open(const std::string& filename, ZipPtr* out_zip) { } PlatformResult Zip::addFile(AddProgressCallback*& callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file(-s) to archive", ("callback is NULL!")); diff --git a/src/archive/zip_add_request.cc b/src/archive/zip_add_request.cc index d376d7a..d8cb38d 100644 --- a/src/archive/zip_add_request.cc +++ b/src/archive/zip_add_request.cc @@ -37,11 +37,11 @@ ZipAddRequest::ZipAddRequest(Zip& owner, AddProgressCallback*& callback) m_bytes_compressed(0), m_compression_level(0), m_new_file_in_zip_opened(false) { - LoggerD("Enter"); + ScopeLogger(); } ZipAddRequest::~ZipAddRequest() { - LoggerD("Enter"); + ScopeLogger(); if (m_input_file) { fclose(m_input_file); m_input_file = NULL; @@ -59,13 +59,13 @@ ZipAddRequest::~ZipAddRequest() { } PlatformResult ZipAddRequest::execute(Zip& owner, AddProgressCallback*& callback) { - LoggerD("Enter"); + ScopeLogger(); ZipAddRequest req(owner, callback); return req.run(); } PlatformResult ZipAddRequest::run() { - LoggerD("Enter"); + ScopeLogger(); if (!m_callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not add file(-s) to archive", ("m_callback is NULL")); @@ -177,7 +177,7 @@ PlatformResult ZipAddRequest::run() { void ZipAddRequest::addNodeAndSubdirsToList(filesystem::NodePtr src_node, filesystem::NodeList& out_list_of_child_nodes) { - LoggerD("Enter"); + ScopeLogger(); out_list_of_child_nodes.push_back(src_node); if (filesystem::NT_DIRECTORY == src_node->getType()) { @@ -193,7 +193,7 @@ void ZipAddRequest::addNodeAndSubdirsToList(filesystem::NodePtr src_node, } PlatformResult ZipAddRequest::addEmptyDirectoryToZipArchive(std::string name_in_zip) { - LoggerD("Entered name_in_zip:%s", name_in_zip.c_str()); + ScopeLogger("name_in_zip: %s", name_in_zip.c_str()); if (name_in_zip.length() == 0) { LoggerW("Trying to create directory with empty name - \"\""); @@ -275,7 +275,7 @@ PlatformResult ZipAddRequest::addEmptyDirectoryToZipArchive(std::string name_in_ } PlatformResult ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) { - LoggerD("Enter"); + ScopeLogger(); const std::string name_in_zip = getNameInZipArchiveFor(src_file_node, m_callback->getFileEntry()->getStriped()); const std::string src_file_path = src_file_node->getPath()->getFullPath(); @@ -441,7 +441,7 @@ PlatformResult ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) } std::string removeDirCharsFromFront(const std::string& path) { - LoggerD("Enter"); + ScopeLogger(); for (size_t i = 0; i < path.length(); ++i) { const char& cur = path[i]; if (cur != '/' && cur != '\\') { @@ -453,7 +453,7 @@ std::string removeDirCharsFromFront(const std::string& path) { } std::string generateFullPathForZip(const std::string& path) { - LoggerD("Enter"); + ScopeLogger(); // Step 1: Remove / from begining const size_t path_len = path.length(); @@ -488,7 +488,7 @@ std::string generateFullPathForZip(const std::string& path) { } std::string ZipAddRequest::getNameInZipArchiveFor(filesystem::NodePtr node, bool strip) { - LoggerD("Enter"); + ScopeLogger(); const std::string node_full_path = node->getPath()->getFullPath(); std::string cut_path; diff --git a/src/badge/badge_instance.cc b/src/badge/badge_instance.cc index bcdcb13..b0ee45b 100644 --- a/src/badge/badge_instance.cc +++ b/src/badge/badge_instance.cc @@ -32,7 +32,7 @@ using namespace common; using namespace extension::badge; BadgeInstance::BadgeInstance() : manager_(*this) { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -45,11 +45,11 @@ BadgeInstance::BadgeInstance() : manager_(*this) { } BadgeInstance::~BadgeInstance() { - LoggerD("Enter"); + ScopeLogger(); } void BadgeInstance::BadgeManagerSetBadgeCount(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); std::string app_id = common::FromJson(args.get(), "appId"); @@ -64,7 +64,7 @@ void BadgeInstance::BadgeManagerSetBadgeCount(const JsonValue& args, JsonObject& } void BadgeInstance::BadgeManagerGetBadgeCount(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); std::string app_id = common::FromJson(args.get(), "appId"); @@ -79,7 +79,7 @@ void BadgeInstance::BadgeManagerGetBadgeCount(const JsonValue& args, JsonObject& } void BadgeInstance::BadgeManagerAddChangeListener(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); PlatformResult status = manager_.AddChangeListener(args.get()); @@ -92,7 +92,7 @@ void BadgeInstance::BadgeManagerAddChangeListener(const JsonValue& args, JsonObj } void BadgeInstance::BadgeManagerRemoveChangeListener(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); PlatformResult status = manager_.RemoveChangeListener(args.get()); diff --git a/src/badge/badge_manager.cc b/src/badge/badge_manager.cc index 54c57b0..fab178e 100644 --- a/src/badge/badge_manager.cc +++ b/src/badge/badge_manager.cc @@ -39,7 +39,7 @@ BadgeManager::BadgeManager(BadgeInstance &instance) } BadgeManager::~BadgeManager() { - LoggerD("Enter"); + ScopeLogger(); if (is_cb_registered_) { if (!watched_applications_.empty()) watched_applications_.clear(); int ret = badge_unregister_changed_cb(badge_changed_cb); @@ -51,7 +51,7 @@ BadgeManager::~BadgeManager() { } PlatformResult BadgeManager::SetBadgeCount(const std::string &app_id, unsigned int count) { - LoggerD("Enter"); + ScopeLogger(); SLoggerD("app_id : %s ", app_id.c_str()); if (!IsAppInstalled(app_id)) { @@ -109,7 +109,7 @@ PlatformResult BadgeManager::SetBadgeCount(const std::string &app_id, unsigned i } PlatformResult BadgeManager::GetBadgeCount(const std::string &app_id, unsigned int *count) { - LoggerD("Enter"); + ScopeLogger(); SLoggerD("app_id : %s ", app_id.c_str()); Assert(count); @@ -158,7 +158,7 @@ PlatformResult BadgeManager::GetBadgeCount(const std::string &app_id, unsigned i } PlatformResult BadgeManager::AddChangeListener(const JsonObject &obj) { - LoggerD("Enter"); + ScopeLogger(); auto &items = FromJson(obj, "appIdList"); for (auto item : items) { watched_applications_.insert(common::JsonCast(item)); @@ -177,7 +177,7 @@ PlatformResult BadgeManager::AddChangeListener(const JsonObject &obj) { } PlatformResult BadgeManager::RemoveChangeListener(const JsonObject &obj) { - LoggerD("Enter"); + ScopeLogger(); auto &items = FromJson(obj, "appIdList"); for (auto item : items) { watched_applications_.erase(common::JsonCast(item)); @@ -196,7 +196,7 @@ PlatformResult BadgeManager::RemoveChangeListener(const JsonObject &obj) { void BadgeManager::badge_changed_cb(unsigned int action, const char *pkgname, unsigned int count, void *user_data) { - LoggerD("Enter"); + ScopeLogger(); BadgeManager *that = static_cast(user_data); if (action == BADGE_ACTION_UPDATE && that->watched_applications_.find(pkgname) != that->watched_applications_.end()) { @@ -211,7 +211,7 @@ void BadgeManager::badge_changed_cb(unsigned int action, const char *pkgname, un } bool BadgeManager::IsAppInstalled(const std::string &app_id) { - LoggerD("Enter"); + ScopeLogger(); if (app_id.empty()) { return false; diff --git a/src/bluetooth/bluetooth_adapter.cc b/src/bluetooth/bluetooth_adapter.cc index f7a0007..9fbf87e 100644 --- a/src/bluetooth/bluetooth_adapter.cc +++ b/src/bluetooth/bluetooth_adapter.cc @@ -77,6 +77,7 @@ const unsigned short kTimeout = 180; } static bool IsValidAddress(const std::string& address) { + ScopeLogger(); static pcrecpp::RE re("(([0-9a-zA-Z]+):)+([0-9a-zA-Z]+)"); static std::string compare_address = "00:12:47:08:9A:A6"; @@ -92,6 +93,7 @@ static bool IsValidAddress(const std::string& address) { } static bool IsValidUUID(const std::string& uuid) { + ScopeLogger(); static pcrecpp::RE re("(([0-9a-zA-Z]+)-)+([0-9a-zA-Z]+)"); static std::string compare_uuid = "00001101-0000-1000-8000-00805F9B34FB"; @@ -109,7 +111,7 @@ static bool IsValidUUID(const std::string& uuid) { } void BluetoothAdapter::StateChangedCB(int result, bt_adapter_state_e state, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); BluetoothAdapter* adapter = static_cast(user_data); if (!adapter) { @@ -165,7 +167,7 @@ void BluetoothAdapter::StateChangedCB(int result, bt_adapter_state_e state, void } void BluetoothAdapter::NameChangedCB(char* name, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); BluetoothAdapter* adapter = static_cast(user_data); if (!adapter) { @@ -191,7 +193,7 @@ void BluetoothAdapter::NameChangedCB(char* name, void* user_data) { void BluetoothAdapter::VisibilityChangedCB(int result, bt_adapter_visibility_mode_e mode, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); BluetoothAdapter* adapter = static_cast(user_data); if (!adapter) { @@ -228,7 +230,7 @@ void BluetoothAdapter::VisibilityChangedCB(int result, bt_adapter_visibility_mod } static bool ForeachBondedDevicesCB(bt_device_info_s* device_info, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); if (nullptr == user_data) { LoggerD("user data is NULL."); return false; @@ -260,7 +262,7 @@ void BluetoothAdapter::DiscoveryStateChangedCB(int result, bt_adapter_device_discovery_state_e discovery_state, bt_adapter_device_discovery_info_s* discovery_info, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); BluetoothAdapter* adapter = static_cast(user_data); if (!adapter) { @@ -360,7 +362,7 @@ BluetoothAdapter::BluetoothAdapter(BluetoothInstance& instance) requested_powered_(), requested_visibility_(), instance_(instance) { - LoggerD("Entered"); + ScopeLogger(); if (BT_ERROR_NONE == bt_initialize()) { LoggerD("Bluetooth service is initialized."); is_initialized_ = true; @@ -390,6 +392,7 @@ BluetoothAdapter::BluetoothAdapter(BluetoothInstance& instance) } BluetoothAdapter::~BluetoothAdapter() { + ScopeLogger(); bt_socket_unset_data_received_cb(); bt_socket_unset_connection_state_changed_cb(); @@ -416,6 +419,7 @@ BluetoothAdapter::~BluetoothAdapter() { } std::string BluetoothAdapter::get_name() const { + ScopeLogger(); char* name = nullptr; std::string str_name = ""; if (BT_ERROR_NONE == bt_adapter_get_name(&name)) { @@ -429,6 +433,7 @@ std::string BluetoothAdapter::get_name() const { } bool BluetoothAdapter::get_visible() const { + ScopeLogger(); bt_adapter_visibility_mode_e mode; if (BT_ERROR_NONE == bt_adapter_get_visibility(&mode, NULL)) { @@ -455,7 +460,7 @@ bool BluetoothAdapter::is_initialized() const { } void BluetoothAdapter::SetName(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, &out); @@ -516,7 +521,7 @@ void BluetoothAdapter::SetName(const picojson::value& data, picojson::object& ou } void BluetoothAdapter::SetPowered(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); LoggerW( "DEPRECATION WARNING: setPowered() is deprecated and will be removed from next release. " "Let the user turn on/off Bluetooth through the Settings application instead."); @@ -635,7 +640,7 @@ void BluetoothAdapter::SetPowered(const picojson::value& data, picojson::object& } void BluetoothAdapter::SetVisible(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothManager, &out); @@ -789,7 +794,7 @@ void BluetoothAdapter::SetVisible(const picojson::value& data, picojson::object& } void BluetoothAdapter::DiscoverDevices(const picojson::value& /* data */, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, &out); @@ -826,7 +831,7 @@ void BluetoothAdapter::DiscoverDevices(const picojson::value& /* data */, picojs } void BluetoothAdapter::StopDiscovery(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, &out); @@ -878,7 +883,7 @@ void BluetoothAdapter::StopDiscovery(const picojson::value& data, picojson::obje } void BluetoothAdapter::GetKnownDevices(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, &out); @@ -933,7 +938,7 @@ void BluetoothAdapter::GetKnownDevices(const picojson::value& data, picojson::ob } void BluetoothAdapter::GetDevice(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, &out); @@ -944,6 +949,7 @@ void BluetoothAdapter::GetDevice(const picojson::value& data, picojson::object& const auto& address = FromJson(args, "address"); auto get_device = [this, address](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function"); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); if (!IsValidAddress(address)) { ret = LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Wrong address"); @@ -995,6 +1001,7 @@ void BluetoothAdapter::GetDevice(const picojson::value& data, picojson::object& auto get_device_response = [this, callback_handle](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function"); instance_.SyncResponse(callback_handle, response); }; @@ -1009,6 +1016,7 @@ class BondingHandler { public: BondingHandler(BluetoothInstance& instance, double callback_handle, const std::string& address) : instance_(instance), callback_handle_(callback_handle), address_(address) { + ScopeLogger(); } void set_address(const std::string& address) { @@ -1020,7 +1028,7 @@ class BondingHandler { } void Invoke(const PlatformResult& result, const std::shared_ptr& response) { - LoggerD("Entered"); + ScopeLogger(); if (result.IsError()) { LogAndReportError(result, &response->get()); @@ -1038,7 +1046,7 @@ class BondingHandler { }; void BluetoothAdapter::CreateBonding(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, &out); @@ -1049,6 +1057,7 @@ void BluetoothAdapter::CreateBonding(const picojson::value& data, picojson::obje const auto& address = FromJson(args, "address"); auto create_bonding = [address, callback_handle, this]() -> void { + ScopeLogger("Entered into asynchronous function, create_bonding"); PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); if (!IsValidAddress(address)) { result = LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Wrong address", @@ -1062,7 +1071,7 @@ void BluetoothAdapter::CreateBonding(const picojson::value& data, picojson::obje if (result.IsSuccess() && this->get_powered()) { auto bond_create_callback = [](int callback_result, bt_device_info_s* device_info, void* user_data) { - LoggerD("bond_create_callback"); + ScopeLogger("Entered into asynchronous function, bond_create_callback"); BondingHandler* handler = static_cast(user_data); if (!handler) { @@ -1154,7 +1163,7 @@ void BluetoothAdapter::CreateBonding(const picojson::value& data, picojson::obje } void BluetoothAdapter::DestroyBonding(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothGap, &out); @@ -1165,6 +1174,7 @@ void BluetoothAdapter::DestroyBonding(const picojson::value& data, picojson::obj const auto& address = FromJson(args, "address"); auto destroy_bonding = [address, callback_handle, this]() -> void { + ScopeLogger("Entered into asynchronous function, destroy_bonding"); PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); if (!IsValidAddress(address)) { result = LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Wrong address", @@ -1265,7 +1275,7 @@ void BluetoothAdapter::DestroyBonding(const picojson::value& data, picojson::obj void BluetoothAdapter::RegisterRFCOMMServiceByUUID(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, &out); @@ -1277,6 +1287,7 @@ void BluetoothAdapter::RegisterRFCOMMServiceByUUID(const picojson::value& data, const auto& name = FromJson(args, "name"); auto rfcomm = [this, uuid, name](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, rfcomm"); PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); if (!this->is_initialized()) { result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Bluetooth service is not initialized."); @@ -1353,6 +1364,7 @@ void BluetoothAdapter::RegisterRFCOMMServiceByUUID(const picojson::value& data, auto rfcomm_response = [this, callback_handle](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, rfcomm_response"); instance_.SyncResponse(callback_handle, response); }; @@ -1364,7 +1376,7 @@ void BluetoothAdapter::RegisterRFCOMMServiceByUUID(const picojson::value& data, } void BluetoothAdapter::UnregisterUUID(const std::string& uuid, int callback_handle) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); if (!IsValidUUID(uuid)) { @@ -1398,7 +1410,7 @@ void BluetoothAdapter::UnregisterUUID(const std::string& uuid, int callback_hand void BluetoothAdapter::GetBluetoothProfileHandler(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const auto& args = util::GetArguments(data); auto profile = FromJson(args, "profileType"); @@ -1430,13 +1442,13 @@ void BluetoothAdapter::GetBluetoothProfileHandler(const picojson::value& data, } void BluetoothAdapter::GetName(const picojson::value& /* data */, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); ReportSuccess(picojson::value(get_name()), out); } void BluetoothAdapter::GetAddress(const picojson::value& /* data */, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); if (!is_initialized_) { LogAndReportError( @@ -1457,20 +1469,20 @@ void BluetoothAdapter::GetAddress(const picojson::value& /* data */, picojson::o } void BluetoothAdapter::GetPowered(const picojson::value& /* data */, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); ReportSuccess(picojson::value(is_powered_), out); } void BluetoothAdapter::GetVisible(const picojson::value& /* data */, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); ReportSuccess(picojson::value(get_visible()), out); } void BluetoothAdapter::OnSocketConnected(int result, bt_socket_connection_state_e state, bt_socket_connection_s* connection, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); BluetoothAdapter* object = static_cast(user_data); @@ -1578,7 +1590,7 @@ void BluetoothAdapter::OnSocketConnected(int result, bt_socket_connection_state_ } void BluetoothAdapter::OnSocketReceivedData(bt_socket_received_data_s* data, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); BluetoothAdapter* object = static_cast(user_data); @@ -1608,7 +1620,7 @@ void BluetoothAdapter::OnSocketReceivedData(bt_socket_received_data_s* data, voi void BluetoothAdapter::ConnectToServiceByUUID(const std::string& address, const std::string& uuid, double callback_handle) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); @@ -1661,6 +1673,7 @@ void BluetoothAdapter::ConnectToServiceByUUID(const std::string& address, const } void BluetoothAdapter::InvokeSocketEvent(int id, const char* event) { + ScopeLogger(); picojson::value value = picojson::value(picojson::object()); picojson::object& value_obj = value.get(); value_obj.insert(std::make_pair("id", picojson::value(std::to_string(id)))); @@ -1669,14 +1682,17 @@ void BluetoothAdapter::InvokeSocketEvent(int id, const char* event) { } void BluetoothAdapter::InvokeSocketOnMessageEvent(int id) { + ScopeLogger(); InvokeSocketEvent(id, "onmessage"); } void BluetoothAdapter::InvokeSocketOnCloseEvent(int id) { + ScopeLogger(); InvokeSocketEvent(id, "onclose"); } void BluetoothAdapter::RemoveSocket(int socket) { + ScopeLogger(); const auto data_it = socket_data_.find(socket); if (data_it != socket_data_.end()) { @@ -1698,7 +1714,7 @@ void BluetoothAdapter::RemoveSocket(int socket) { } void BluetoothAdapter::StoreSocketData(bt_socket_received_data_s* data) { - LoggerD("Entered"); + ScopeLogger(); auto& data_store = socket_data_[data->socket_fd]; @@ -1708,13 +1724,13 @@ void BluetoothAdapter::StoreSocketData(bt_socket_received_data_s* data) { } const std::list& BluetoothAdapter::ReadSocketData(int socket) { - LoggerD("Entered"); + ScopeLogger(); return socket_data_[socket]; } void BluetoothAdapter::ClearSocketData(int socket) { - LoggerD("Entered"); + ScopeLogger(); const auto data_it = socket_data_.find(socket); @@ -1724,7 +1740,7 @@ void BluetoothAdapter::ClearSocketData(int socket) { } void BluetoothAdapter::IsServiceConnected(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const auto& args = util::GetArguments(data); const auto& uuid = FromJson(args, "uuid"); diff --git a/src/bluetooth/bluetooth_class.cc b/src/bluetooth/bluetooth_class.cc index 976c151..4a56131 100644 --- a/src/bluetooth/bluetooth_class.cc +++ b/src/bluetooth/bluetooth_class.cc @@ -120,7 +120,7 @@ std::map g_service_enum_map = { {BT_MAJOR_SERVICE_CLASS_INFORMATION, 0x0400}}; unsigned long BluetoothClass::GetMajorValue(bt_major_device_class_e major) { - LoggerD("Enter"); + ScopeLogger(); auto iter = g_major_enum_map.find(major); if (iter != g_major_enum_map.end()) { return iter->second; @@ -130,7 +130,7 @@ unsigned long BluetoothClass::GetMajorValue(bt_major_device_class_e major) { } unsigned long BluetoothClass::GetMinorValue(bt_minor_device_class_e minor) { - LoggerD("Enter"); + ScopeLogger(); auto iter = g_minor_enum_map.find(minor); if (iter != g_minor_enum_map.end()) { return iter->second; @@ -140,7 +140,7 @@ unsigned long BluetoothClass::GetMinorValue(bt_minor_device_class_e minor) { } std::vector BluetoothClass::getServiceValues(int serviceMask) { - LoggerD("Enter"); + ScopeLogger(); std::vector ret; for (auto iter = g_service_enum_map.begin(); iter != g_service_enum_map.end(); iter++) { if (iter->first & serviceMask) { diff --git a/src/bluetooth/bluetooth_device.cc b/src/bluetooth/bluetooth_device.cc index 0f82b45..b686530 100644 --- a/src/bluetooth/bluetooth_device.cc +++ b/src/bluetooth/bluetooth_device.cc @@ -47,7 +47,7 @@ const std::string kDeviceIsConnected = "isConnected"; } static void ToJsonFromBTClass(bt_class_s bluetooth_class, picojson::object* device) { - LoggerD("Entered"); + ScopeLogger(); picojson::object& bt = device->insert(std::make_pair(kDeviceClass, picojson::value(picojson::object()))) @@ -73,7 +73,7 @@ static void ToJsonFromBTClass(bt_class_s bluetooth_class, picojson::object* devi } static void ToJsonFromUUID(char** service_uuid, int service_count, picojson::object* device) { - LoggerD("Entered"); + ScopeLogger(); picojson::array& array = device->insert(std::make_pair(kDeviceUuids, picojson::value(picojson::array()))) @@ -85,10 +85,11 @@ static void ToJsonFromUUID(char** service_uuid, int service_count, picojson::obj } BluetoothDevice::BluetoothDevice(BluetoothAdapter& adapter) : adapter_(adapter) { + ScopeLogger(); } void BluetoothDevice::ToJson(bt_device_info_s* info, picojson::object* device) { - LoggerD("Entered"); + ScopeLogger(); device->insert(std::make_pair(kDeviceName, picojson::value(std::string(info->remote_name)))); device->insert( std::make_pair(kDeviceAddress, picojson::value(std::string(info->remote_address)))); @@ -98,7 +99,7 @@ void BluetoothDevice::ToJson(bt_device_info_s* info, picojson::object* device) { } void BluetoothDevice::ToJson(bt_adapter_device_discovery_info_s* info, picojson::object* device) { - LoggerD("Entered"); + ScopeLogger(); device->insert(std::make_pair(kDeviceName, picojson::value(info->remote_name))); device->insert(std::make_pair(kDeviceAddress, picojson::value(info->remote_address))); @@ -108,7 +109,7 @@ void BluetoothDevice::ToJson(bt_adapter_device_discovery_info_s* info, picojson: } void BluetoothDevice::ConnectToServiceByUUID(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, &out); @@ -123,7 +124,7 @@ void BluetoothDevice::ConnectToServiceByUUID(const picojson::value& data, picojs } void BluetoothDevice::GetBoolValue(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const auto& args = util::GetArguments(data); const auto& address = FromJson(args, "address"); diff --git a/src/bluetooth/bluetooth_gatt_service.cc b/src/bluetooth/bluetooth_gatt_service.cc index eaa7894..14f4bc7 100644 --- a/src/bluetooth/bluetooth_gatt_service.cc +++ b/src/bluetooth/bluetooth_gatt_service.cc @@ -59,11 +59,11 @@ bool IsProperty(int propertyBits, bt_gatt_property_e property) { } BluetoothGATTService::BluetoothGATTService(BluetoothInstance& instance) : instance_(instance) { - LoggerD("Entered"); + ScopeLogger(); } BluetoothGATTService::~BluetoothGATTService() { - LoggerD("Entered"); + ScopeLogger(); for (auto it : gatt_characteristic_) { // unregister callback, ignore errors @@ -82,7 +82,7 @@ bool BluetoothGATTService::IsStillConnected(const std::string& address) { } bt_gatt_client_h BluetoothGATTService::GetGattClient(const std::string& address) { - LoggerD("Entered"); + ScopeLogger(); bt_gatt_client_h client = nullptr; @@ -105,6 +105,7 @@ bt_gatt_client_h BluetoothGATTService::GetGattClient(const std::string& address) // this method should be used to inform this object that some device was disconnected void BluetoothGATTService::TryDestroyClient(const std::string& address) { + ScopeLogger(); auto it = gatt_clients_.find(address); if (gatt_clients_.end() != it) { LoggerD("destroying client for address: %s", it->first.c_str()); @@ -118,7 +119,7 @@ void BluetoothGATTService::TryDestroyClient(const std::string& address) { PlatformResult BluetoothGATTService::GetSpecifiedGATTService(const std::string& address, const std::string& uuid, picojson::object* result) { - LoggerD("Entered"); + ScopeLogger(); bt_gatt_client_h client = GetGattClient(address); @@ -158,7 +159,7 @@ PlatformResult BluetoothGATTService::GetSpecifiedGATTService(const std::string& } void BluetoothGATTService::GetServices(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); bt_gatt_h handle = (bt_gatt_h) static_cast(args.get("handle").get()); const std::string& address = args.get("address").get(); @@ -174,7 +175,7 @@ void BluetoothGATTService::GetServices(const picojson::value& args, picojson::ob PlatformResult BluetoothGATTService::GetServicesHelper(bt_gatt_h handle, const std::string& address, picojson::array* array) { - LoggerD("Entered"); + ScopeLogger(); if (!IsStillConnected(address)) { return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected", @@ -184,7 +185,9 @@ PlatformResult BluetoothGATTService::GetServicesHelper(bt_gatt_h handle, const s int ret = bt_gatt_service_foreach_included_services( handle, [](int total, int index, bt_gatt_h gatt_handle, void* data) { - LoggerD("Enter"); + ScopeLogger( + "Entered into asynchronous function, argument in " + "bt_gatt_service_foreach_included_services"); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); @@ -213,7 +216,7 @@ PlatformResult BluetoothGATTService::GetServicesHelper(bt_gatt_h handle, const s } void BluetoothGATTService::GetCharacteristics(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); bt_gatt_h handle = (bt_gatt_h) static_cast(args.get("handle").get()); const std::string& uuid = args.get("uuid").get(); @@ -232,7 +235,7 @@ PlatformResult BluetoothGATTService::GetCharacteristicsHelper(bt_gatt_h handle, const std::string& address, const std::string& uuid, picojson::array* array) { - LoggerD("Entered"); + ScopeLogger(); if (!IsStillConnected(address)) { return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected", @@ -250,7 +253,9 @@ PlatformResult BluetoothGATTService::GetCharacteristicsHelper(bt_gatt_h handle, int ret = bt_gatt_service_foreach_characteristics( handle, [](int total, int index, bt_gatt_h gatt_handle, void* data) { - LoggerD("Enter"); + ScopeLogger( + "Entered into asynchronous function, bt_gatt_service_foreach_characteristics's " + "argument"); Data* user_data = static_cast(data); picojson::array* array = user_data->array; PlatformResult* platform_result = user_data->platform_res; @@ -268,7 +273,7 @@ PlatformResult BluetoothGATTService::GetCharacteristicsHelper(bt_gatt_h handle, int ret = bt_gatt_characteristic_foreach_descriptors( gatt_handle, [](int total, int index, bt_gatt_h desc_handle, void* data) { - LoggerD("Enter"); + ScopeLogger(); picojson::array& desc_array = *(static_cast(data)); picojson::value desc = picojson::value(picojson::object()); @@ -328,7 +333,7 @@ PlatformResult BluetoothGATTService::GetCharacteristicsHelper(bt_gatt_h handle, } void BluetoothGATTService::ReadValue(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, &out); @@ -349,6 +354,7 @@ void BluetoothGATTService::ReadValue(const picojson::value& args, picojson::obje bt_gatt_h handle = (bt_gatt_h) static_cast(args.get("handle").get()); auto read_value = [](int result, bt_gatt_h handle, void* user_data) -> void { + ScopeLogger("Entered into asynchronous function, read_value"); Data* data = static_cast(user_data); double callback_handle = data->callback_handle; BluetoothGATTService* service = data->service; @@ -401,7 +407,7 @@ void BluetoothGATTService::ReadValue(const picojson::value& args, picojson::obje } void BluetoothGATTService::WriteValue(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, &out); @@ -429,6 +435,7 @@ void BluetoothGATTService::WriteValue(const picojson::value& args, picojson::obj bt_gatt_h handle = (bt_gatt_h) static_cast(args.get("handle").get()); auto write_value = [](int result, bt_gatt_h handle, void* user_data) -> void { + ScopeLogger("Entered into asynchronous function, write_value"); Data* data = static_cast(user_data); double callback_handle = data->callback_handle; BluetoothGATTService* service = data->service; @@ -479,7 +486,7 @@ void BluetoothGATTService::WriteValue(const picojson::value& args, picojson::obj void BluetoothGATTService::AddValueChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const auto& address = args.get("address").get(); if (!IsStillConnected(address)) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected"), &out, @@ -503,7 +510,7 @@ void BluetoothGATTService::AddValueChangeListener(const picojson::value& args, void BluetoothGATTService::RemoveValueChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const auto& address = args.get("address").get(); if (!IsStillConnected(address)) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Device is not connected"), &out, @@ -530,7 +537,7 @@ void BluetoothGATTService::RemoveValueChangeListener(const picojson::value& args common::PlatformResult BluetoothGATTService::GetServiceAllUuids(const std::string& address, picojson::array* array) { - LoggerD("Entered"); + ScopeLogger(); bt_gatt_client_h client = GetGattClient(address); @@ -539,7 +546,8 @@ common::PlatformResult BluetoothGATTService::GetServiceAllUuids(const std::strin } auto foreach_callback = [](int total, int index, bt_gatt_h gatt_handle, void* user_data) -> bool { - LoggerD("Entered foreach_callback, total: %d, index: %d", total, index); + ScopeLogger("Entered into asynchronous function, foreach_callback, total: %d, index: %d", total, + index); char* uuid = nullptr; int ret = bt_gatt_get_uuid(gatt_handle, &uuid); @@ -569,8 +577,8 @@ common::PlatformResult BluetoothGATTService::GetServiceAllUuids(const std::strin void BluetoothGATTService::OnCharacteristicValueChanged(bt_gatt_h characteristic, char* value, int length, void* user_data) { - LoggerD("Entered, characteristic: [%p], len: [%d], user_data: [%p]", characteristic, length, - user_data); + ScopeLogger("characteristic: [%p], len: [%d], user_data: [%p]", characteristic, length, + user_data); auto service = static_cast(user_data); diff --git a/src/bluetooth/bluetooth_health_application.cc b/src/bluetooth/bluetooth_health_application.cc index 7d347f7..7b58724 100644 --- a/src/bluetooth/bluetooth_health_application.cc +++ b/src/bluetooth/bluetooth_health_application.cc @@ -38,10 +38,11 @@ using namespace common; BluetoothHealthApplication::BluetoothHealthApplication(BluetoothHealthProfileHandler& handler) : handler_(handler) { + ScopeLogger(); } void BluetoothHealthApplication::Unregister(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothHealth, &out); @@ -56,6 +57,7 @@ void BluetoothHealthApplication::Unregister(const picojson::value& data, picojso void BluetoothHealthApplication::ToJson(short data_type, const std::string& name, const char* id, picojson::object* out) { + ScopeLogger(); out->insert(std::make_pair(kDataType, picojson::value(static_cast(data_type)))); out->insert(std::make_pair(kName, picojson::value(name))); out->insert(std::make_pair(kId, picojson::value(id))); diff --git a/src/bluetooth/bluetooth_health_channel.cc b/src/bluetooth/bluetooth_health_channel.cc index da7f6f6..8d19279 100644 --- a/src/bluetooth/bluetooth_health_channel.cc +++ b/src/bluetooth/bluetooth_health_channel.cc @@ -42,7 +42,7 @@ const std::string kId = "_id"; } // namespace void BluetoothHealthChannel::Close(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothHealth, &out); @@ -63,7 +63,7 @@ void BluetoothHealthChannel::Close(const picojson::value& data, picojson::object } void BluetoothHealthChannel::SendData(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothHealth, &out); @@ -92,7 +92,7 @@ void BluetoothHealthChannel::SendData(const picojson::value& data, picojson::obj void BluetoothHealthChannel::ToJson(unsigned int channel, bt_hdp_channel_type_e type, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); const char* type_str = "UNKNOWN"; switch (type) { @@ -117,7 +117,7 @@ void BluetoothHealthChannel::ToJson(unsigned int channel, bt_hdp_channel_type_e void BluetoothHealthChannel::ToJson(unsigned int channel, bt_hdp_channel_type_e type, bt_device_info_s* device_info, const char* app_id, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); ToJson(channel, type, out); auto& device = out->insert(std::make_pair(kPeer, picojson::value(picojson::object()))) .first->second.get(); diff --git a/src/bluetooth/bluetooth_health_profile_handler.cc b/src/bluetooth/bluetooth_health_profile_handler.cc index 7581eef..2aeacb5 100644 --- a/src/bluetooth/bluetooth_health_profile_handler.cc +++ b/src/bluetooth/bluetooth_health_profile_handler.cc @@ -48,7 +48,7 @@ const std::string kChangeCallback = "BluetoothHealthChannelChangeCallback"; BluetoothHealthProfileHandler::BluetoothHealthProfileHandler(BluetoothInstance& instance) : instance_(instance) { // initialize listeners - LoggerD("Entered"); + ScopeLogger(); if (BT_ERROR_NONE != bt_hdp_set_connection_state_changed_cb(OnConnected, OnDisconnected, this)) { LoggerE("bt_hdp_set_connection_state_changed_cb() failed"); } @@ -59,7 +59,7 @@ BluetoothHealthProfileHandler::BluetoothHealthProfileHandler(BluetoothInstance& } BluetoothHealthProfileHandler::~BluetoothHealthProfileHandler() { - LoggerD("Entered"); + ScopeLogger(); bt_hdp_unset_connection_state_changed_cb(); bt_hdp_unset_data_received_cb(); @@ -71,7 +71,7 @@ BluetoothHealthProfileHandler::~BluetoothHealthProfileHandler() { void BluetoothHealthProfileHandler::OnConnected(int result, const char* remote_address, const char* app_id, bt_hdp_channel_type_e type, unsigned int channel, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); BluetoothHealthProfileHandler* object = static_cast(user_data); @@ -162,7 +162,7 @@ void BluetoothHealthProfileHandler::OnConnected(int result, const char* remote_a void BluetoothHealthProfileHandler::OnDisconnected(int result, const char* /* remote_address */, unsigned int channel, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); BluetoothHealthProfileHandler* object = static_cast(user_data); @@ -185,7 +185,7 @@ void BluetoothHealthProfileHandler::OnDisconnected(int result, const char* /* re void BluetoothHealthProfileHandler::OnDataReceived(unsigned int channel, const char* data, unsigned int size, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); BluetoothHealthProfileHandler* object = static_cast(user_data); @@ -216,7 +216,7 @@ void BluetoothHealthProfileHandler::OnDataReceived(unsigned int channel, const c void BluetoothHealthProfileHandler::RegisterSinkApp(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothHealth, &out); @@ -229,7 +229,7 @@ void BluetoothHealthProfileHandler::RegisterSinkApp(const picojson::value& data, auto register_app = [data_type, name, this](const std::shared_ptr& response) -> void { - LoggerD("Entered"); + ScopeLogger(); PlatformResult platform_result = PlatformResult(ErrorCode::NO_ERROR); char* app_id = nullptr; @@ -266,6 +266,7 @@ void BluetoothHealthProfileHandler::RegisterSinkApp(const picojson::value& data, auto register_app_response = [this, callback_handle](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, register_app_response"); instance_.SyncResponse(callback_handle, response); }; @@ -278,7 +279,7 @@ void BluetoothHealthProfileHandler::RegisterSinkApp(const picojson::value& data, void BluetoothHealthProfileHandler::ConnectToSource(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothHealth, &out); @@ -332,10 +333,10 @@ void BluetoothHealthProfileHandler::ConnectToSource(const picojson::value& data, void BluetoothHealthProfileHandler::UnregisterSinkAppAsync(const std::string& app_id, int callback_handle) { - LoggerD("Entered"); + ScopeLogger(); auto unregister_app = [app_id, this](const std::shared_ptr& response) -> void { - LoggerD("Entered"); + ScopeLogger("Entered into asynchronous function, uregister_app"); PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); auto iter = this->registered_health_apps_.find(app_id); @@ -376,6 +377,7 @@ void BluetoothHealthProfileHandler::UnregisterSinkAppAsync(const std::string& ap auto unregister_app_response = [this, callback_handle](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, unregister_app_response"); instance_.SyncResponse(callback_handle, response); }; diff --git a/src/bluetooth/bluetooth_instance.cc b/src/bluetooth/bluetooth_instance.cc index 3082985..a3dd135 100644 --- a/src/bluetooth/bluetooth_instance.cc +++ b/src/bluetooth/bluetooth_instance.cc @@ -37,7 +37,7 @@ BluetoothInstance::BluetoothInstance() bluetooth_le_adapter_(*this), bluetooth_gatt_service_(*this), bluetooth_le_device_(*this, bluetooth_gatt_service_) { - LoggerD("Entered"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -166,7 +166,7 @@ BluetoothInstance::BluetoothInstance() } BluetoothInstance::~BluetoothInstance() { - LoggerD("Entered"); + ScopeLogger(); } namespace { @@ -176,7 +176,7 @@ const char* JSON_LISTENER_ID = "listenerId"; void BluetoothInstance::AsyncResponse(double callback_handle, const std::shared_ptr& response) { - LoggerD("Entered"); + ScopeLogger(); common::TaskQueue::GetInstance().Async( [this, callback_handle](const std::shared_ptr& response) { SyncResponse(callback_handle, response); @@ -185,7 +185,7 @@ void BluetoothInstance::AsyncResponse(double callback_handle, } void BluetoothInstance::AsyncResponse(double callback_handle, const PlatformResult& result) { - LoggerD("Entered"); + ScopeLogger(); std::shared_ptr response = std::shared_ptr(new picojson::value(picojson::object())); @@ -197,6 +197,7 @@ void BluetoothInstance::AsyncResponse(double callback_handle, const PlatformResu TaskQueue::GetInstance().Async( [this, callback_handle](const std::shared_ptr& response) { + ScopeLogger("Entered into asynchronous response"); SyncResponse(callback_handle, response); }, response); @@ -204,28 +205,28 @@ void BluetoothInstance::AsyncResponse(double callback_handle, const PlatformResu void BluetoothInstance::SyncResponse(double callback_handle, const std::shared_ptr& response) { - LoggerD("Entered"); + ScopeLogger(); auto& obj = response->get(); obj[JSON_CALLBACK_ID] = picojson::value(callback_handle); Instance::PostMessage(this, response->serialize().c_str()); } void BluetoothInstance::FireEvent(const std::string& event, picojson::value& value) { - LoggerD("Entered"); + ScopeLogger(); auto& obj = value.get(); obj[JSON_LISTENER_ID] = picojson::value(event); Instance::PostMessage(this, value.serialize().c_str()); } void BluetoothInstance::FireEvent(const std::string& event, const picojson::value& value) { - LoggerD("Entered"); + ScopeLogger(); picojson::value v{value}; FireEvent(event, v); } void BluetoothInstance::FireEvent(const std::string& event, const std::shared_ptr& value) { - LoggerD("Entered"); + ScopeLogger(); FireEvent(event, *value.get()); } diff --git a/src/bluetooth/bluetooth_le_adapter.cc b/src/bluetooth/bluetooth_le_adapter.cc index 58efa13..83dabfc 100644 --- a/src/bluetooth/bluetooth_le_adapter.cc +++ b/src/bluetooth/bluetooth_le_adapter.cc @@ -32,8 +32,10 @@ namespace { class ParsedDataHolder { public: ParsedDataHolder() : valid_(false) { + ScopeLogger(); } virtual ~ParsedDataHolder() { + ScopeLogger(); } bool valid() const { @@ -55,6 +57,7 @@ class HexData { } void Parse(const std::string& d) { + ScopeLogger(); const char* p_data = d.c_str(); int size = d.length(); if (size > 2 && (d.find("0x", 0) == 0 || d.find("0X", 0) == 0)) { @@ -101,7 +104,7 @@ class BluetoothLEServiceData : public ParsedDataHolder { private: static bool ParseUUID(const picojson::value& obj, BluetoothLEServiceData* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& uuid = obj.get("uuid"); if (uuid.is()) { out->uuid_ = uuid.get(); @@ -113,7 +116,7 @@ class BluetoothLEServiceData : public ParsedDataHolder { } static bool ParseData(const picojson::value& obj, BluetoothLEServiceData* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& data = obj.get("data"); if (data.is()) { out->data_.Parse(data.get()); @@ -139,7 +142,7 @@ class BluetoothLEManufacturerData : public ParsedDataHolder { } static bool Construct(const picojson::value& obj, BluetoothLEManufacturerData* out) { - LoggerD("Entered"); + ScopeLogger(); if (!obj.is() || !ParseId(obj, out) || !ParseData(obj, out)) { return false; } @@ -151,7 +154,7 @@ class BluetoothLEManufacturerData : public ParsedDataHolder { private: static bool ParseId(const picojson::value& obj, BluetoothLEManufacturerData* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& id = obj.get("id"); if (id.is()) { out->id_ = id.get(); @@ -163,7 +166,7 @@ class BluetoothLEManufacturerData : public ParsedDataHolder { } static bool ParseData(const picojson::value& obj, BluetoothLEManufacturerData* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& val_data = obj.get("data"); @@ -186,6 +189,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { include_name_(false), appearance_(0), // 0 means unknown include_tx_power_level_(false) { + ScopeLogger(); } bool include_name() const { @@ -217,7 +221,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { } static bool Construct(const picojson::value& obj, BluetoothLEAdvertiseData* out) { - LoggerD("Entered"); + ScopeLogger(); if (!obj.is() || !ParseIncludeName(obj, out) || !ParseServiceUUIDs(obj, out) || !ParseSolicitationUUIDs(obj, out) || !ParseAppearance(obj, out) || !ParseIncludeTxPowerLevel(obj, out) || @@ -232,7 +236,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { private: static bool ParseIncludeName(const picojson::value& obj, BluetoothLEAdvertiseData* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& include_name = obj.get("includeName"); if (include_name.is()) { out->include_name_ = include_name.get(); @@ -244,7 +248,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { } static bool ParseServiceUUIDs(const picojson::value& obj, BluetoothLEAdvertiseData* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& service_uuids = obj.get("uuids"); if (service_uuids.is()) { for (const auto& i : service_uuids.get()) { @@ -262,7 +266,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { } static bool ParseSolicitationUUIDs(const picojson::value& obj, BluetoothLEAdvertiseData* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& solicitation_uuids = obj.get("solicitationuuids"); if (solicitation_uuids.is()) { for (const auto& i : solicitation_uuids.get()) { @@ -280,7 +284,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { } static bool ParseAppearance(const picojson::value& obj, BluetoothLEAdvertiseData* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& appearance = obj.get("appearance"); if (appearance.is()) { out->appearance_ = static_cast(appearance.get()); @@ -292,7 +296,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { } static bool ParseIncludeTxPowerLevel(const picojson::value& obj, BluetoothLEAdvertiseData* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& include_tx_power_level = obj.get("includeTxPowerLevel"); if (include_tx_power_level.is()) { out->include_tx_power_level_ = include_tx_power_level.get(); @@ -304,7 +308,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { } static bool ParseServiceData(const picojson::value& obj, BluetoothLEAdvertiseData* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& service_data = obj.get("serviceData"); BluetoothLEServiceData data; if (BluetoothLEServiceData::Construct(service_data, &data)) { @@ -317,7 +321,7 @@ class BluetoothLEAdvertiseData : public ParsedDataHolder { } static bool ParseManufacturerData(const picojson::value& obj, BluetoothLEAdvertiseData* out) { - LoggerD("Entered"); + ScopeLogger(); const auto& manufacturer_data = obj.get("manufacturerData"); BluetoothLEManufacturerData data; if (BluetoothLEManufacturerData::Construct(manufacturer_data, &data)) { @@ -366,7 +370,7 @@ using common::tools::ReportSuccess; BluetoothLEAdapter::BluetoothLEAdapter(BluetoothInstance& instance) : instance_(instance), enabled_(false), scanning_(false), bt_advertiser_(nullptr) { - LoggerD("Entered"); + ScopeLogger(); bt_adapter_le_state_e le_state = BT_ADAPTER_LE_DISABLED; @@ -385,7 +389,7 @@ BluetoothLEAdapter::BluetoothLEAdapter(BluetoothInstance& instance) } BluetoothLEAdapter::~BluetoothLEAdapter() { - LoggerD("Entered"); + ScopeLogger(); bt_adapter_le_unset_state_changed_cb(); if (scanning_) { bt_adapter_le_stop_scan(); @@ -397,7 +401,7 @@ BluetoothLEAdapter::~BluetoothLEAdapter() { } void BluetoothLEAdapter::StartScan(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, &out); @@ -423,7 +427,7 @@ void BluetoothLEAdapter::StartScan(const picojson::value& data, picojson::object } void BluetoothLEAdapter::StopScan(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, &out); @@ -439,7 +443,7 @@ void BluetoothLEAdapter::StopScan(const picojson::value& data, picojson::object& } void BluetoothLEAdapter::StartAdvertise(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, &out); @@ -638,7 +642,7 @@ void BluetoothLEAdapter::StartAdvertise(const picojson::value& data, picojson::o } void BluetoothLEAdapter::StopAdvertise(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, &out); @@ -661,7 +665,7 @@ void BluetoothLEAdapter::StopAdvertise(const picojson::value& data, picojson::ob void BluetoothLEAdapter::OnStateChanged(int result, bt_adapter_le_state_e adapter_le_state, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); auto adapter = static_cast(user_data); @@ -675,7 +679,7 @@ void BluetoothLEAdapter::OnStateChanged(int result, bt_adapter_le_state_e adapte void BluetoothLEAdapter::OnScanResult(int result, bt_adapter_le_device_scan_result_info_s* info, void* user_data) { - LoggerD("Entered, result: %d, info: %p, data: %p", result, info, user_data); + ScopeLogger("result: %d, info: %p, data: %p", result, info, user_data); auto adapter = static_cast(user_data); @@ -714,8 +718,8 @@ void BluetoothLEAdapter::OnScanResult(int result, bt_adapter_le_device_scan_resu void BluetoothLEAdapter::OnAdvertiseResult(int result, bt_advertiser_h advertiser, bt_adapter_le_advertising_state_e adv_state, void* user_data) { - LoggerD("Entered, result: %d, advertiser: %p, adv_state: %d, user_data: %p", result, advertiser, - adv_state, user_data); + ScopeLogger("result: %d, advertiser: %p, adv_state: %d, user_data: %p", result, advertiser, + adv_state, user_data); auto adapter = static_cast(user_data); diff --git a/src/bluetooth/bluetooth_le_device.cc b/src/bluetooth/bluetooth_le_device.cc index 34e2964..c10ebc8 100644 --- a/src/bluetooth/bluetooth_le_device.cc +++ b/src/bluetooth/bluetooth_le_device.cc @@ -57,7 +57,7 @@ const std::string kConnectChangeEvent = "BluetoothLEConnectChangeCallback"; BluetoothLEDevice::BluetoothLEDevice(BluetoothInstance& instance, BluetoothGATTService& service) : instance_(instance), service_(service), is_listener_set_(false) { - LoggerD("Entered"); + ScopeLogger(); int ret = bt_gatt_set_connection_state_changed_cb(GattConnectionState, this); if (BT_ERROR_NONE != ret && BT_ERROR_ALREADY_DONE != ret) { LoggerE("Can't add connection state listener: %d", ret); @@ -65,7 +65,7 @@ BluetoothLEDevice::BluetoothLEDevice(BluetoothInstance& instance, BluetoothGATTS } BluetoothLEDevice::~BluetoothLEDevice() { - LoggerD("Entered"); + ScopeLogger(); int ret = bt_gatt_unset_connection_state_changed_cb(); if (ret != BT_ERROR_NONE) { LoggerW("Failed to unset listener: %d", ret); @@ -74,7 +74,7 @@ BluetoothLEDevice::~BluetoothLEDevice() { static void UUIDsToJson(char** service_uuid, int service_count, const std::string& field, picojson::object* le_device) { - LoggerD("Entered"); + ScopeLogger(); picojson::array& array = le_device->insert(std::make_pair(field, picojson::value(picojson::array()))) @@ -87,7 +87,7 @@ static void UUIDsToJson(char** service_uuid, int service_count, const std::strin static void ServiceDataToJson(bt_adapter_le_service_data_s* service_data_list, int service_data_list_count, picojson::object* le_device) { - LoggerD("Entered"); + ScopeLogger(); picojson::array& array = le_device->insert(std::make_pair(kServiceData, picojson::value(picojson::array()))) @@ -113,7 +113,7 @@ static void ServiceDataToJson(bt_adapter_le_service_data_s* service_data_list, static void ManufacturerToJson(int manufacturer_id, char* manufacturer_data, int manufacturer_count, picojson::object* le_device) { - LoggerD("Entered"); + ScopeLogger(); picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); @@ -132,7 +132,7 @@ static void ManufacturerToJson(int manufacturer_id, char* manufacturer_data, int PlatformResult BluetoothLEDevice::ToJson(bt_adapter_le_device_scan_result_info_s* info, picojson::object* le_device) { - LoggerD("Entered"); + ScopeLogger(); le_device->insert( std::make_pair(kDeviceAddress, picojson::value(std::string(info->remote_address)))); @@ -283,7 +283,7 @@ PlatformResult BluetoothLEDevice::ToJson(bt_adapter_le_device_scan_result_info_s } void BluetoothLEDevice::Connect(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, &out); @@ -320,7 +320,7 @@ void BluetoothLEDevice::Connect(const picojson::value& data, picojson::object& o } void BluetoothLEDevice::Disconnect(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, &out); @@ -362,7 +362,7 @@ void BluetoothLEDevice::Disconnect(const picojson::value& data, picojson::object } void BluetoothLEDevice::GetService(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothAdmin, &out); @@ -393,8 +393,6 @@ void BluetoothLEDevice::GetService(const picojson::value& data, picojson::object void BluetoothLEDevice::AddConnectStateChangeListener(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); - is_listener_set_ = true; ReportSuccess(out); @@ -402,15 +400,13 @@ void BluetoothLEDevice::AddConnectStateChangeListener(const picojson::value& dat void BluetoothLEDevice::RemoveConnectStateChangeListener(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); - is_listener_set_ = false; ReportSuccess(out); } void BluetoothLEDevice::GetServiceAllUuids(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const auto& args = util::GetArguments(data); const auto& address = common::FromJson(args, "address"); @@ -429,7 +425,7 @@ void BluetoothLEDevice::GetServiceAllUuids(const picojson::value& data, picojson void BluetoothLEDevice::GattConnectionState(int result, bool connected, const char* remote_address, void* user_data) { - LoggerD("Entered: %s connected: %d", remote_address, connected); + ScopeLogger("%s connected: %d", remote_address, connected); auto le_device = static_cast(user_data); if (!le_device) { diff --git a/src/bluetooth/bluetooth_service_handler.cc b/src/bluetooth/bluetooth_service_handler.cc index d249f89..8e27097 100644 --- a/src/bluetooth/bluetooth_service_handler.cc +++ b/src/bluetooth/bluetooth_service_handler.cc @@ -34,7 +34,7 @@ BluetoothServiceHandler::BluetoothServiceHandler(BluetoothAdapter& adapter) : ad } void BluetoothServiceHandler::Unregister(const picojson::value& data, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, &out); diff --git a/src/bluetooth/bluetooth_socket.cc b/src/bluetooth/bluetooth_socket.cc index 3d4a8c1..7625ae4 100644 --- a/src/bluetooth/bluetooth_socket.cc +++ b/src/bluetooth/bluetooth_socket.cc @@ -45,10 +45,11 @@ using namespace common; using namespace common::tools; BluetoothSocket::BluetoothSocket(BluetoothAdapter& adapter) : adapter_(adapter) { + ScopeLogger(); } void BluetoothSocket::WriteData(const picojson::value& data, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, &out); @@ -75,7 +76,7 @@ void BluetoothSocket::WriteData(const picojson::value& data, picojson::object& o } void BluetoothSocket::ReadData(const picojson::value& data, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, &out); @@ -98,7 +99,7 @@ void BluetoothSocket::ReadData(const picojson::value& data, picojson::object& ou } void BluetoothSocket::Close(const picojson::value& data, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_BACKWARD_COMPABILITY_PRIVILEGE_ACCESS(Privilege::kBluetooth, Privilege::kBluetoothSpp, &out); @@ -117,7 +118,7 @@ void BluetoothSocket::Close(const picojson::value& data, picojson::object& out) } picojson::value BluetoothSocket::ToJson(bt_socket_connection_s* connection) { - LoggerD("Enter"); + ScopeLogger(); picojson::value ret = picojson::value(picojson::object()); auto& ret_obj = ret.get(); diff --git a/src/bookmark/bookmark_instance.cc b/src/bookmark/bookmark_instance.cc index e600e55..884dba1 100644 --- a/src/bookmark/bookmark_instance.cc +++ b/src/bookmark/bookmark_instance.cc @@ -42,7 +42,7 @@ const std::string kPrivilegeBookmarkWrite = "http://tizen.org/privilege/bookmark } // namespace BookmarkInstance::BookmarkInstance() { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -56,11 +56,11 @@ BookmarkInstance::BookmarkInstance() { } BookmarkInstance::~BookmarkInstance() { - LoggerD("Enter"); + ScopeLogger(); } bool BookmarkInstance::bookmark_foreach(Context& ctx, bp_bookmark_info_fmt& info) { - LoggerD("Enter"); + ScopeLogger(); int ids_count = 0; int* ids = NULL; BookmarkObject item; @@ -84,7 +84,7 @@ bool BookmarkInstance::bookmark_foreach(Context& ctx, bp_bookmark_info_fmt& info } PlatformResult BookmarkInstance::BookmarkUrlExists(const char* url, bool* exists) { - LoggerD("Enter"); + ScopeLogger(); int ids_count = 0; int* ids = nullptr; char* compare_url = nullptr; @@ -131,7 +131,7 @@ PlatformResult BookmarkInstance::BookmarkUrlExists(const char* url, bool* exists PlatformResult BookmarkInstance::BookmarkTitleExistsInParent(const char* title, int parent, bool* exists) { - LoggerD("Enter"); + ScopeLogger(); int ids_count = 0; int compare_parent = -1; int* ids = nullptr; @@ -182,9 +182,9 @@ PlatformResult BookmarkInstance::BookmarkTitleExistsInParent(const char* title, } void BookmarkInstance::BookmarkGet(const picojson::value& arg, picojson::object& o) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeBookmarkRead, &o); - LoggerD("Enter"); Context ctx = {0}; bp_bookmark_info_fmt info = {0}; picojson::value::array arr; @@ -214,9 +214,9 @@ void BookmarkInstance::BookmarkGet(const picojson::value& arg, picojson::object& } void BookmarkInstance::BookmarkAdd(const picojson::value& arg, picojson::object& o) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeBookmarkWrite, &o); - LoggerD("Enter"); int saved_id = -1; const auto& title = arg.get(kTitle).get(); @@ -289,9 +289,9 @@ void BookmarkInstance::BookmarkAdd(const picojson::value& arg, picojson::object& } void BookmarkInstance::BookmarkRemove(const picojson::value& arg, picojson::object& o) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeBookmarkWrite, &o); - LoggerD("Enter"); int id = common::stol(common::FromJson(arg.get(), kId)); int ntv_ret = bp_bookmark_adaptor_delete(id); @@ -303,9 +303,9 @@ void BookmarkInstance::BookmarkRemove(const picojson::value& arg, picojson::obje } void BookmarkInstance::BookmarkRemoveAll(const picojson::value& msg, picojson::object& o) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeBookmarkWrite, &o); - LoggerD("Enter"); int ntv_ret = bp_bookmark_adaptor_reset(); if (ntv_ret < 0) { LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to remove bookmark"), &o); @@ -315,7 +315,7 @@ void BookmarkInstance::BookmarkRemoveAll(const picojson::value& msg, picojson::o } void BookmarkInstance::BookmarkGetRootId(const picojson::value& msg, picojson::object& o) { - LoggerD("Enter"); + ScopeLogger(); int rootId(0); int ntv_ret = bp_bookmark_adaptor_get_root(&rootId); if (ntv_ret < 0) { diff --git a/src/calendar/calendar.cc b/src/calendar/calendar.cc index 0995fdb..ef161c0 100644 --- a/src/calendar/calendar.cc +++ b/src/calendar/calendar.cc @@ -41,9 +41,11 @@ void CalendarFilterDeleter(calendar_filter_h calendar_filter) { using namespace common; Calendar::Calendar(CalendarInstance& instance) : current_db_version_(0), instance_(instance) { + ScopeLogger(); } Calendar::~Calendar() { + ScopeLogger(); int ret; if (listeners_registered_.find("EVENT") != listeners_registered_.end()) { @@ -62,6 +64,7 @@ Calendar::~Calendar() { } PlatformResult Calendar::Get(const picojson::object& args, picojson::object& out) { + ScopeLogger(); if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -102,6 +105,7 @@ PlatformResult Calendar::Get(const picojson::object& args, picojson::object& out } PlatformResult Calendar::Add(const picojson::object& args, picojson::object& out) { + ScopeLogger(); if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -141,6 +145,7 @@ PlatformResult Calendar::Add(const picojson::object& args, picojson::object& out } PlatformResult Calendar::AddBatch(const picojson::object& args, picojson::array& array) { + ScopeLogger(); if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -215,6 +220,7 @@ PlatformResult Calendar::AddBatch(const picojson::object& args, picojson::array& } PlatformResult Calendar::Update(const picojson::object& args, picojson::object& /*out*/) { + ScopeLogger(); if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -297,6 +303,7 @@ PlatformResult Calendar::Update(const picojson::object& args, picojson::object& } PlatformResult Calendar::UpdateBatch(const picojson::object& args, picojson::array& array) { + ScopeLogger(); if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -367,6 +374,7 @@ PlatformResult Calendar::UpdateBatch(const picojson::object& args, picojson::arr } PlatformResult Calendar::Remove(const picojson::object& args, picojson::object& out) { + ScopeLogger(); if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -384,7 +392,7 @@ PlatformResult Calendar::Remove(const picojson::object& args, picojson::object& } PlatformResult Calendar::SetDefaultFilter(calendar_query_h* calendar_query, int type, int id) { - LoggerD("Entered"); + ScopeLogger(); const long UNIFIED_CALENDAR_ID = 0; int error_code = 0; @@ -423,6 +431,7 @@ PlatformResult Calendar::SetDefaultFilter(calendar_query_h* calendar_query, int } PlatformResult Calendar::Find(const picojson::object& args, picojson::array& array) { + ScopeLogger(); if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -452,6 +461,7 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr FilterVisitor visitor; visitor.SetOnAttributeFilter([&](const std::string& name, AttributeMatchFlag match_flag, const picojson::value& match_value) { + ScopeLogger("Entered into asynchronous function, visitor.SetOnAttributeFilter' argument"); int value = 0; calendar_filter_h calendar_filter = nullptr; @@ -558,12 +568,15 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr return PlatformResult(ErrorCode::NO_ERROR); }); visitor.SetOnCompositeFilterBegin([&](CompositeFilterType type) { + ScopeLogger( + "Entered into asynchronous function, visitor.SetOnCompositeFilterBegin's argument"); intermediate_filters.push_back(std::vector()); return PlatformResult(ErrorCode::NO_ERROR); }); visitor.SetOnCompositeFilterEnd([&](CompositeFilterType calType) { + ScopeLogger("Entered into asynchronous function, visitor.SetOnCompositeFilterEnd's argument"); if (intermediate_filters.size() == 0) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Reached stack size equal to 0!"); } @@ -596,6 +609,8 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr visitor.SetOnAttributeRangeFilter([&](const std::string& name, const JsonValue& initial_value, const JsonValue& end_value) { + ScopeLogger( + "Entered into asynchronous function, visitor.SetOnAttributeRangeFilter's argument"); unsigned int propertyId = 0; if (name == "startDate" || name == "endDate" || name == "dueDate") { PlatformResult status = @@ -842,6 +857,7 @@ PlatformResult Calendar::Find(const picojson::object& args, picojson::array& arr } PlatformResult Calendar::RemoveBatch(const picojson::object& args, picojson::array& array) { + ScopeLogger(); if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -907,6 +923,7 @@ PlatformResult Calendar::RemoveBatch(const picojson::object& args, picojson::arr } PlatformResult Calendar::AddChangeListener(const picojson::object& args, picojson::object& out) { + ScopeLogger(); if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -942,6 +959,7 @@ PlatformResult Calendar::AddChangeListener(const picojson::object& args, picojso } PlatformResult Calendar::RemoveChangeListener(const picojson::object& args, picojson::object& out) { + ScopeLogger(); if (!CalendarManager::GetInstance().IsConnected()) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -966,7 +984,7 @@ PlatformResult Calendar::RemoveChangeListener(const picojson::object& args, pico } void Calendar::ChangeCallback(const char* view_uri, void* user_data) { - LoggerD("enter"); + ScopeLogger(); Calendar* c = static_cast(user_data); diff --git a/src/calendar/calendar_instance.cc b/src/calendar/calendar_instance.cc index 66c1777..c1a7e96 100644 --- a/src/calendar/calendar_instance.cc +++ b/src/calendar/calendar_instance.cc @@ -40,7 +40,7 @@ using namespace common; using namespace extension::calendar; CalendarInstance::CalendarInstance() : calendar_(*this) { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -71,11 +71,11 @@ CalendarInstance::CalendarInstance() : calendar_(*this) { } CalendarInstance::~CalendarInstance() { - LoggerD("Enter"); + ScopeLogger(); } void CalendarInstance::CalendarGet(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarRead, &out); JsonValue val{JsonObject{}}; @@ -90,7 +90,7 @@ void CalendarInstance::CalendarGet(const JsonValue& args, JsonObject& out) { } void CalendarInstance::CalendarAdd(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); JsonValue val{JsonObject{}}; @@ -105,7 +105,7 @@ void CalendarInstance::CalendarAdd(const JsonValue& args, JsonObject& out) { } void CalendarInstance::CalendarAddBatch(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); const double callback_id = args.get("callbackId").get(); @@ -123,7 +123,7 @@ void CalendarInstance::CalendarAddBatch(const JsonValue& args, JsonObject& out) }; auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { - LoggerD("CalendarAddBatch->get_response"); + ScopeLogger("Entered into asynchronous function, CalendarAddBatch->get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); LoggerD("callback is %s", response->serialize().c_str()); @@ -136,7 +136,7 @@ void CalendarInstance::CalendarAddBatch(const JsonValue& args, JsonObject& out) } void CalendarInstance::CalendarUpdate(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); JsonValue val{JsonObject{}}; @@ -152,12 +152,13 @@ void CalendarInstance::CalendarUpdate(const JsonValue& args, JsonObject& out) { } void CalendarInstance::CalendarUpdateBatch(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { - LoggerD("CalendarUpdateBatch->get"); + ScopeLogger("Entered into asynchronous function, CalendarUpdateBatch->get"); + JsonValue result = JsonValue(JsonArray()); PlatformResult status = calendar_.UpdateBatch(common::JsonCast(args), result.get()); @@ -170,7 +171,8 @@ void CalendarInstance::CalendarUpdateBatch(const JsonValue& args, JsonObject& ou }; auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { - LoggerD("CalendarUpdateBatch->get_response"); + ScopeLogger("Entered into asynchronous function, CalendarUpdateBatch->get_response"); + picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); LoggerD("callback is %s", response->serialize().c_str()); @@ -183,7 +185,7 @@ void CalendarInstance::CalendarUpdateBatch(const JsonValue& args, JsonObject& ou } void CalendarInstance::CalendarRemove(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); JsonValue val{JsonObject{}}; @@ -199,12 +201,13 @@ void CalendarInstance::CalendarRemove(const JsonValue& args, JsonObject& out) { } void CalendarInstance::CalendarRemoveBatch(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { - LoggerD("CalendarRemoveBatch->get"); + ScopeLogger("Entered into asynchronous function, CalendarRemoveBatch->get"); + JsonValue result = JsonValue(JsonArray()); PlatformResult status = calendar_.RemoveBatch(common::JsonCast(args), result.get()); @@ -217,7 +220,8 @@ void CalendarInstance::CalendarRemoveBatch(const JsonValue& args, JsonObject& ou }; auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { - LoggerD("CalendarRemoveBatch->get_response"); + ScopeLogger("Entered into asynchronous function, CalendarRemoveBatch->get_response"); + picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); LoggerD("callback is %s", response->serialize().c_str()); @@ -230,12 +234,13 @@ void CalendarInstance::CalendarRemoveBatch(const JsonValue& args, JsonObject& ou } void CalendarInstance::CalendarFind(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarRead, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { - LoggerD("CalendarFind->get"); + ScopeLogger("Entered into asynchronous function, CalendarFind->get"); + JsonValue result = JsonValue(JsonArray()); PlatformResult status = calendar_.Find(common::JsonCast(args), result.get()); @@ -248,10 +253,11 @@ void CalendarInstance::CalendarFind(const JsonValue& args, JsonObject& out) { }; auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { - LoggerD("CalendarFind->get_response"); + ScopeLogger("Entered into asynchronous function, CalendarFind->get_response"); + picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); - LoggerD("callback isssssss %s", response->serialize().c_str()); + LoggerD("callback is %s", response->serialize().c_str()); Instance::PostMessage(this, response->serialize().c_str()); }; @@ -261,7 +267,7 @@ void CalendarInstance::CalendarFind(const JsonValue& args, JsonObject& out) { } void CalendarInstance::CalendarAddChangeListener(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarRead, &out); JsonValue val{JsonObject{}}; @@ -277,7 +283,7 @@ void CalendarInstance::CalendarAddChangeListener(const JsonValue& args, JsonObje } void CalendarInstance::CalendarRemoveChangeListener(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarRead, &out); JsonValue val{JsonObject{}}; @@ -294,7 +300,7 @@ void CalendarInstance::CalendarRemoveChangeListener(const JsonValue& args, JsonO // CalendarManager void CalendarInstance::CalendarManagerAddCalendar(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); JsonValue val{JsonObject{}}; @@ -309,7 +315,7 @@ void CalendarInstance::CalendarManagerAddCalendar(const JsonValue& args, JsonObj } void CalendarInstance::CalendarManagerGetCalendar(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarRead, &out); JsonValue val{JsonObject{}}; @@ -324,12 +330,13 @@ void CalendarInstance::CalendarManagerGetCalendar(const JsonValue& args, JsonObj } void CalendarInstance::CalendarManagerGetCalendars(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarRead, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { - LoggerD("CalendarManagerGetCalendars->get"); + ScopeLogger("Entered into asynchronous function, CalendarManagerGetCalendars->get"); + JsonValue result = JsonValue(JsonArray()); PlatformResult status = CalendarManager::GetInstance().GetCalendars( @@ -343,7 +350,8 @@ void CalendarInstance::CalendarManagerGetCalendars(const JsonValue& args, JsonOb }; auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { - LoggerD("CalendarManagerGetCalendars->get_response"); + ScopeLogger("Entered into asynchronous function, CalendarManagerGetCalendars->get_response"); + picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); LoggerD("callback is %s", response->serialize().c_str()); @@ -356,7 +364,7 @@ void CalendarInstance::CalendarManagerGetCalendars(const JsonValue& args, JsonOb } void CalendarInstance::CalendarManagerRemoveCalendar(const JsonValue& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCalendarWrite, &out); JsonValue val{JsonObject{}}; diff --git a/src/calendar/calendar_item.cc b/src/calendar/calendar_item.cc index be2eda7..6ac5c8c 100644 --- a/src/calendar/calendar_item.cc +++ b/src/calendar/calendar_item.cc @@ -193,7 +193,7 @@ const PlatformEnumMap CalendarItem::platform_enum_map_ = { PlatformEnumReverseMap CalendarItem::platform_enum_reverse_map_ = {}; PlatformResult CalendarItem::Create(int type, calendar_record_h* handle) { - LoggerD("Enter"); + ScopeLogger(); std::string value_str; PlatformResult status = CalendarRecord::TypeToUri(type, &value_str); if (status.IsError()) { @@ -204,7 +204,7 @@ PlatformResult CalendarItem::Create(int type, calendar_record_h* handle) { } PlatformResult CalendarItem::Remove(int type, int id) { - LoggerD("Enter"); + ScopeLogger(); std::string view_uri; PlatformResult status = CalendarRecord::TypeToUri(type, &view_uri); if (status.IsError()) { @@ -245,7 +245,7 @@ PlatformResult CalendarItem::Remove(int type, int id) { PlatformResult CalendarItem::GetPlatformProperty(int type, const std::string& property, unsigned int* value) { - LoggerD("Enter"); + ScopeLogger(); if (platform_property_map_.find(property) == platform_property_map_.end()) { std::string message = std::string("Undefined property ") + property; return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, message); @@ -265,7 +265,7 @@ PlatformResult CalendarItem::GetPlatformProperty(int type, const std::string& pr PlatformResult CalendarItem::StringToPlatformEnum(const std::string& field, const std::string& value, int* platform_enum) { - LoggerD("Enter"); + ScopeLogger(); auto iter = platform_enum_map_.find(field); if (iter == platform_enum_map_.end()) { std::string message = std::string("Undefined platform enum type ") + field; @@ -292,7 +292,7 @@ PlatformResult CalendarItem::StringToPlatformEnum(const std::string& field, PlatformResult CalendarItem::PlatformEnumToString(const std::string& field, int value, std::string* platform_str) { - LoggerD("Enter"); + ScopeLogger(); // @todo can be replaced by Boost.Bimap if (platform_enum_reverse_map_.empty()) { for (auto& def : platform_enum_map_) { @@ -325,7 +325,7 @@ PlatformResult CalendarItem::PlatformEnumToString(const std::string& field, int PlatformResult CalendarItem::SetString(int type, calendar_record_h rec, const std::string& property, const picojson::object& in, bool optional) { - LoggerD("set: %s", property.c_str()); + ScopeLogger("set: %s", property.c_str()); if (optional && IsNull(in, property.c_str())) { return PlatformResult(ErrorCode::NO_ERROR); @@ -338,7 +338,7 @@ PlatformResult CalendarItem::SetString(int type, calendar_record_h rec, const st PlatformResult CalendarItem::SetString(int type, calendar_record_h rec, const std::string& property, const std::string& value) { - LoggerD("set: %s", property.c_str()); + ScopeLogger("set: %s", property.c_str()); unsigned int prop; PlatformResult status = GetPlatformProperty(type, property, &prop); @@ -358,7 +358,7 @@ PlatformResult CalendarItem::SetString(int type, calendar_record_h rec, const st PlatformResult CalendarItem::GetString(int type, calendar_record_h rec, const std::string& property, std::string* value) { - LoggerD("get: %s", property.c_str()); + ScopeLogger("set: %s", property.c_str()); unsigned int prop; PlatformResult status = GetPlatformProperty(type, property, &prop); @@ -371,7 +371,7 @@ PlatformResult CalendarItem::GetString(int type, calendar_record_h rec, const st PlatformResult CalendarItem::SetInt(int type, calendar_record_h rec, const std::string& property, const picojson::object& in, bool optional) { - LoggerD("set: %s", property.c_str()); + ScopeLogger("set: %s", property.c_str()); if (optional && IsNull(in, property.c_str())) { return PlatformResult(ErrorCode::NO_ERROR); @@ -384,7 +384,7 @@ PlatformResult CalendarItem::SetInt(int type, calendar_record_h rec, const std:: PlatformResult CalendarItem::SetInt(int type, calendar_record_h rec, const std::string& property, int value) { - LoggerD("set: %s", property.c_str()); + ScopeLogger("set: %s" + property); unsigned int prop; PlatformResult status = GetPlatformProperty(type, property, &prop); @@ -397,7 +397,7 @@ PlatformResult CalendarItem::SetInt(int type, calendar_record_h rec, const std:: PlatformResult CalendarItem::GetInt(int type, calendar_record_h rec, const std::string& property, int* value) { - LoggerD("get: %s", property.c_str()); + ScopeLogger("set: %s" + property); unsigned int prop; PlatformResult status = GetPlatformProperty(type, property, &prop); @@ -410,7 +410,7 @@ PlatformResult CalendarItem::GetInt(int type, calendar_record_h rec, const std:: PlatformResult CalendarItem::SetEnum(int type, calendar_record_h rec, const std::string& property, const picojson::object& in, const std::string& enum_name) { - LoggerD("Enter"); + ScopeLogger(); std::string value = common::FromJson(in, property.c_str()); int value_int; @@ -429,7 +429,7 @@ PlatformResult CalendarItem::SetEnum(int type, calendar_record_h rec, const std: PlatformResult CalendarItem::SetEnum(calendar_record_h rec, unsigned int property, const std::string& enum_name, const std::string& value) { - LoggerD("Enter"); + ScopeLogger(); int value_int; PlatformResult status = StringToPlatformEnum(enum_name, value, &value_int); if (status.IsError()) { @@ -446,6 +446,7 @@ PlatformResult CalendarItem::SetEnum(calendar_record_h rec, unsigned int propert PlatformResult CalendarItem::GetEnum(int type, calendar_record_h rec, const std::string& property, const std::string& enum_name, std::string* enum_str) { + ScopeLogger(); int value; PlatformResult status = GetInt(type, rec, property, &value); if (status.IsError()) { @@ -457,7 +458,7 @@ PlatformResult CalendarItem::GetEnum(int type, calendar_record_h rec, const std: PlatformResult CalendarItem::GetEnum(calendar_record_h rec, unsigned int property, const std::string& enum_name, std::string* enum_str) { - LoggerD("Enter"); + ScopeLogger(); int value; PlatformResult status = CalendarRecord::GetInt(rec, property, &value); if (status.IsError()) { @@ -469,7 +470,7 @@ PlatformResult CalendarItem::GetEnum(calendar_record_h rec, unsigned int propert PlatformResult CalendarItem::SetDouble(int type, calendar_record_h rec, const std::string& property, double value) { - LoggerD("set: %s", property.c_str()); + ScopeLogger("set: %s", property.c_str()); unsigned int prop; PlatformResult status = GetPlatformProperty(type, property, &prop); @@ -489,7 +490,7 @@ PlatformResult CalendarItem::SetDouble(int type, calendar_record_h rec, const st PlatformResult CalendarItem::GetDouble(int type, calendar_record_h rec, const std::string& property, double* value) { - LoggerD("get: %s", property.c_str()); + ScopeLogger("get: %s", property.c_str()); unsigned int prop; PlatformResult status = GetPlatformProperty(type, property, &prop); @@ -510,7 +511,7 @@ PlatformResult CalendarItem::GetDouble(int type, calendar_record_h rec, const st PlatformResult CalendarItem::SetCaltime(int type, calendar_record_h rec, const std::string& property, calendar_time_s value, bool throw_on_error) { - LoggerD("Enter"); + ScopeLogger(); unsigned int prop; PlatformResult status = GetPlatformProperty(type, property, &prop); if (status.IsError()) { @@ -522,7 +523,7 @@ PlatformResult CalendarItem::SetCaltime(int type, calendar_record_h rec, PlatformResult CalendarItem::SetCaltime(calendar_record_h rec, unsigned int property, calendar_time_s value, bool throw_on_error) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_record_set_caltime(rec, property, value); if (CALENDAR_ERROR_NONE != ret) { @@ -540,7 +541,7 @@ PlatformResult CalendarItem::SetCaltime(calendar_record_h rec, unsigned int prop PlatformResult CalendarItem::GetCaltime(int type, calendar_record_h rec, const std::string& property, calendar_time_s* cal_time, bool throw_on_error) { - LoggerD("get: %s", property.c_str()); + ScopeLogger("set: %s" + property); unsigned int prop; PlatformResult status = GetPlatformProperty(type, property, &prop); @@ -553,7 +554,7 @@ PlatformResult CalendarItem::GetCaltime(int type, calendar_record_h rec, PlatformResult CalendarItem::GetCaltime(calendar_record_h rec, unsigned int property, calendar_time_s* cal_time, bool throw_on_error) { - LoggerD("Enter"); + ScopeLogger(); if (property != -1u) { int ret = calendar_record_get_caltime(rec, property, cal_time); if (CALENDAR_ERROR_NONE != ret) { @@ -570,7 +571,7 @@ PlatformResult CalendarItem::GetCaltime(calendar_record_h rec, unsigned int prop PlatformResult CalendarItem::SetLli(calendar_record_h rec, unsigned int property, long long int value, bool throw_on_error) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_record_set_lli(rec, property, value); if (CALENDAR_ERROR_NONE != ret) { @@ -587,7 +588,7 @@ PlatformResult CalendarItem::SetLli(calendar_record_h rec, unsigned int property PlatformResult CalendarItem::GetLli(int type, calendar_record_h rec, const std::string& property, long long int* lli) { - LoggerD("get: %s", property.c_str()); + ScopeLogger("set: %s" + property); unsigned int prop; PlatformResult status = GetPlatformProperty(type, property, &prop); @@ -600,7 +601,7 @@ PlatformResult CalendarItem::GetLli(int type, calendar_record_h rec, const std:: PlatformResult CalendarItem::GetLli(calendar_record_h rec, unsigned int property, long long int* value, bool throw_on_error) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_record_get_lli(rec, property, value); if (CALENDAR_ERROR_NONE != ret) { LoggerW("Can't get lli value form record: %d", ret); @@ -614,7 +615,7 @@ PlatformResult CalendarItem::GetLli(calendar_record_h rec, unsigned int property } Date CalendarItem::DateFromJson(const picojson::object& in) { - LoggerD("json date %s", picojson::value(in).serialize().c_str()); + ScopeLogger("json date " + picojson::value(in).serialize()); Date date = {(long long int)common::FromJson(in, "UTCTimestamp"), (int)common::FromJson(in, "year"), @@ -625,12 +626,12 @@ Date CalendarItem::DateFromJson(const picojson::object& in) { } Date CalendarItem::DateFromJson(const picojson::object& in, const char* obj_name) { - LoggerD("Enter"); + ScopeLogger(); return DateFromJson(common::FromJson(in, obj_name)); } picojson::value CalendarItem::DateToJson(Date* date) { - LoggerD("timestamp: %lld", date->utc_timestamp_); + ScopeLogger("timestamp: %lld", date->utc_timestamp_); picojson::value date_val = picojson::value(picojson::object()); picojson::object& date_obj = date_val.get(); @@ -646,7 +647,7 @@ picojson::value CalendarItem::DateToJson(Date* date) { PlatformResult CalendarItem::CategoriesFromJson(int type, calendar_record_h rec, const picojson::array& value) { - LoggerD("Enter"); + ScopeLogger(); std::string categories = ""; for (auto iter = value.begin(); iter != value.end(); ++iter) { if (iter == value.begin()) { @@ -666,7 +667,7 @@ PlatformResult CalendarItem::CategoriesFromJson(int type, calendar_record_h rec, PlatformResult CalendarItem::CategoriesToJson(int type, calendar_record_h rec, picojson::array* value) { - LoggerD("Enter"); + ScopeLogger(); std::string categories; PlatformResult status = GetString(type, rec, "categories", &categories); if (status.IsError()) { @@ -680,7 +681,7 @@ PlatformResult CalendarItem::CategoriesToJson(int type, calendar_record_h rec, PlatformResult CalendarItem::AttendeesFromJson(int type, calendar_record_h rec, const picojson::array& value) { - LoggerD("Enter"); + ScopeLogger(); // Remove the preset child attendees before adding new ones. unsigned int property; if (type == CALENDAR_BOOK_TYPE_EVENT) { @@ -792,7 +793,7 @@ PlatformResult CalendarItem::AttendeesFromJson(int type, calendar_record_h rec, PlatformResult CalendarItem::AttendeesToJson(int type, calendar_record_h rec, picojson::array* out) { - LoggerD("Enter"); + ScopeLogger(); unsigned int property; if (type == CALENDAR_BOOK_TYPE_EVENT) { property = _calendar_event.calendar_attendee; @@ -914,7 +915,7 @@ PlatformResult CalendarItem::AttendeesToJson(int type, calendar_record_h rec, PlatformResult CalendarItem::AlarmsFromJson(int type, calendar_record_h rec, const picojson::array& alarms) { - LoggerD("Enter"); + ScopeLogger(); unsigned int property; if (type == CALENDAR_BOOK_TYPE_EVENT) { property = _calendar_event.calendar_alarm; @@ -1012,7 +1013,7 @@ PlatformResult CalendarItem::AlarmsFromJson(int type, calendar_record_h rec, } PlatformResult CalendarItem::AlarmsToJson(int type, calendar_record_h rec, picojson::array* out) { - LoggerD("Enter"); + ScopeLogger(); unsigned int property; if (type == CALENDAR_BOOK_TYPE_EVENT) { property = _calendar_event.calendar_alarm; @@ -1115,7 +1116,7 @@ PlatformResult CalendarItem::AlarmsToJson(int type, calendar_record_h rec, picoj PlatformResult CalendarItem::RecurrenceRuleFromJson(calendar_record_h rec, const picojson::object& rrule) { - LoggerD("Enter"); + ScopeLogger(); const std::string& frequency = common::FromJson(rrule, "frequency"); PlatformResult status = SetEnum(rec, _calendar_event.freq, kRecurrenceRuleFrequency, frequency); if (status.IsError()) { @@ -1198,7 +1199,7 @@ PlatformResult CalendarItem::RecurrenceRuleFromJson(calendar_record_h rec, } std::string CalendarItem::ExceptionsFromJson(const picojson::array& exceptions) { - LoggerD("Enter"); + ScopeLogger(); std::string result; Date date; for (auto iter = exceptions.begin(); iter != exceptions.end(); ++iter) { @@ -1219,7 +1220,7 @@ std::string CalendarItem::ExceptionsFromJson(const picojson::array& exceptions) PlatformResult CalendarItem::RecurrenceRuleToJson(calendar_record_h rec, picojson::object* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); picojson::object& out = *out_ptr; std::string enum_str; @@ -1300,7 +1301,7 @@ PlatformResult CalendarItem::RecurrenceRuleToJson(calendar_record_h rec, } calendar_time_s CalendarItem::DateToPlatform(const Date& date, bool is_all_day) { - LoggerD("Enter"); + ScopeLogger(); calendar_time_s cal; if (is_all_day) { @@ -1317,7 +1318,7 @@ calendar_time_s CalendarItem::DateToPlatform(const Date& date, bool is_all_day) PlatformResult CalendarItem::DateFromPlatform(int type, calendar_record_h rec, const std::string& property, Date* date_from_platform) { - LoggerD("Enter"); + ScopeLogger(); calendar_time_s cal; PlatformResult status = GetCaltime(type, rec, property + "_time", &cal); if (status.IsError()) { @@ -1341,7 +1342,7 @@ PlatformResult CalendarItem::DateFromPlatform(int type, calendar_record_h rec, PlatformResult CalendarItem::DateFromPlatform(calendar_record_h rec, unsigned int property, Date* date_from_platform) { - LoggerD("Enter"); + ScopeLogger(); calendar_time_s cal; PlatformResult status = GetCaltime(rec, property, &cal); if (status.IsError()) { @@ -1358,7 +1359,7 @@ PlatformResult CalendarItem::DateFromPlatform(calendar_record_h rec, unsigned in } PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, const picojson::object& in) { - LoggerD("Enter"); + ScopeLogger(); if (in.empty()) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Empty Calendar object."); } @@ -1514,7 +1515,7 @@ PlatformResult CalendarItem::FromJson(int type, calendar_record_h rec, const pic } PlatformResult CalendarItem::ToJson(int type, calendar_record_h rec, picojson::object* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); if (NULL == rec) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Calendar record is null"); } @@ -1722,7 +1723,7 @@ PlatformResult CalendarItem::ToJson(int type, calendar_record_h rec, picojson::o } picojson::array CalendarItem::StringToArray(const std::string& string) { - LoggerD("Enter"); + ScopeLogger(); picojson::array out = picojson::array(); size_t cstr_length = string.length() + 1; diff --git a/src/calendar/calendar_manager.cc b/src/calendar/calendar_manager.cc index 5de0579..4c2edaf 100644 --- a/src/calendar/calendar_manager.cc +++ b/src/calendar/calendar_manager.cc @@ -37,7 +37,7 @@ const int kUnifiedCalendardId = 0; using namespace common; CalendarManager::CalendarManager() { - LoggerD("Enter"); + ScopeLogger(); if (CALENDAR_ERROR_NONE == calendar_connect()) { LoggerD("Calendar DB connected"); is_connected_ = true; @@ -47,7 +47,7 @@ CalendarManager::CalendarManager() { } CalendarManager::~CalendarManager() { - LoggerD("Enter"); + ScopeLogger(); if (is_connected_) { if (CALENDAR_ERROR_NONE == calendar_disconnect()) { LoggerD("Calendar DB disconnected"); @@ -58,7 +58,7 @@ CalendarManager::~CalendarManager() { } CalendarManager& CalendarManager::GetInstance() { - LoggerD("Enter"); + ScopeLogger(); static CalendarManager instance; return instance; } @@ -68,7 +68,7 @@ bool CalendarManager::IsConnected() { } PlatformResult CalendarManager::GetCalendars(const JsonObject& args, JsonArray& array) { - LoggerD("Enter"); + ScopeLogger(); if (!is_connected_) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -138,7 +138,7 @@ PlatformResult CalendarManager::GetCalendars(const JsonObject& args, JsonArray& } PlatformResult CalendarManager::GetCalendar(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); if (!is_connected_) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -174,7 +174,7 @@ PlatformResult CalendarManager::GetCalendar(const JsonObject& args, JsonObject& } PlatformResult CalendarManager::AddCalendar(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); if (!is_connected_) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } @@ -205,7 +205,7 @@ PlatformResult CalendarManager::AddCalendar(const JsonObject& args, JsonObject& } PlatformResult CalendarManager::RemoveCalendar(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); if (!is_connected_) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "DB Connection failed."); } diff --git a/src/calendar/calendar_plugin.cc b/src/calendar/calendar_plugin.cc index cf466e7..3d3fe8f 100644 --- a/src/calendar/calendar_plugin.cc +++ b/src/calendar/calendar_plugin.cc @@ -36,15 +36,18 @@ class CalendarPlugin : public NativePlugin { EXPORT_NATIVE_PLUGIN(webapi::calendar::CalendarPlugin); CalendarPlugin::CalendarPlugin() { + ScopeLogger(); manager_ = &CalendarManager::GetInstance(); calendar_ = &Calendar::GetInstance(); } CalendarPlugin::~CalendarPlugin() { + ScopeLogger(); manager_ = nullptr; } void CalendarPlugin::OnLoad() { + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; diff --git a/src/calendar/calendar_record.cc b/src/calendar/calendar_record.cc index d8e6b98..87926f5 100644 --- a/src/calendar/calendar_record.cc +++ b/src/calendar/calendar_record.cc @@ -32,7 +32,7 @@ const std::string kCalendarTypeTask = "TASK"; using namespace common; PlatformResult CalendarRecord::CheckReturn(int ret, const std::string& error_name) { - LoggerD("Enter"); + ScopeLogger(); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, error_name, ("%s : %d (%s)", error_name.c_str(), ret, get_error_message(ret))); @@ -42,7 +42,7 @@ PlatformResult CalendarRecord::CheckReturn(int ret, const std::string& error_nam } void CalendarRecord::QueryDeleter(calendar_query_h handle) { - LoggerD("Enter"); + ScopeLogger(); if (handle) { if (CALENDAR_ERROR_NONE != calendar_query_destroy(handle)) { LoggerW("calendar_query_destroy failed"); @@ -51,7 +51,7 @@ void CalendarRecord::QueryDeleter(calendar_query_h handle) { } void CalendarRecord::Deleter(calendar_record_h handle) { - LoggerD("Enter"); + ScopeLogger(); if (handle) { if (CALENDAR_ERROR_NONE != calendar_record_destroy(handle, true)) { LoggerW("calendar_record_destroy failed"); @@ -60,7 +60,7 @@ void CalendarRecord::Deleter(calendar_record_h handle) { } void CalendarRecord::ListDeleter(calendar_list_h handle) { - LoggerD("Enter"); + ScopeLogger(); if (handle) { if (CALENDAR_ERROR_NONE != calendar_list_destroy(handle, true)) { LoggerW("calendar_list_destroy failed"); @@ -70,7 +70,7 @@ void CalendarRecord::ListDeleter(calendar_list_h handle) { PlatformResult CalendarRecord::GetString(calendar_record_h rec, unsigned int property, std::string* str, bool throw_on_error) { - LoggerD("Enter"); + ScopeLogger(); char* value = NULL; int ret = calendar_record_get_str(rec, property, &value); if (CALENDAR_ERROR_NONE != ret) { @@ -91,7 +91,7 @@ PlatformResult CalendarRecord::GetString(calendar_record_h rec, unsigned int pro PlatformResult CalendarRecord::SetString(calendar_record_h record, unsigned int property, const std::string& value, bool throw_on_error) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_record_set_str(record, property, value.empty() ? NULL : value.c_str()); if (CALENDAR_ERROR_NONE != ret) { @@ -106,7 +106,7 @@ PlatformResult CalendarRecord::SetString(calendar_record_h record, unsigned int PlatformResult CalendarRecord::GetInt(calendar_record_h rec, unsigned int property, int* value, bool throw_on_error) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_record_get_int(rec, property, value); if (CALENDAR_ERROR_NONE != ret) { LoggerE("Can't get int value form record: %d (%s)", ret, get_error_message(ret)); @@ -120,7 +120,7 @@ PlatformResult CalendarRecord::GetInt(calendar_record_h rec, unsigned int proper PlatformResult CalendarRecord::SetInt(calendar_record_h record, unsigned int property, int value, bool throw_on_error) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_record_set_int(record, property, value); if (CALENDAR_ERROR_NONE != ret) { @@ -134,7 +134,7 @@ PlatformResult CalendarRecord::SetInt(calendar_record_h record, unsigned int pro } std::string CalendarRecord::TypeToString(int type) { - LoggerD("Enter"); + ScopeLogger(); if (CALENDAR_BOOK_TYPE_EVENT == type) { return kCalendarTypeEvent; } @@ -147,7 +147,7 @@ std::string CalendarRecord::TypeToString(int type) { } std::string CalendarRecord::TypeToString(const char* view_uri) { - LoggerD("Enter"); + ScopeLogger(); if (0 == strcmp(view_uri, _calendar_event._uri)) { return kCalendarTypeEvent; } @@ -159,7 +159,7 @@ std::string CalendarRecord::TypeToString(const char* view_uri) { } int CalendarRecord::TypeToInt(const std::string& type) { - LoggerD("Enter"); + ScopeLogger(); if (kCalendarTypeEvent == type) { return CALENDAR_BOOK_TYPE_EVENT; } @@ -171,7 +171,7 @@ int CalendarRecord::TypeToInt(const std::string& type) { } int CalendarRecord::TypeToInt(const char* view_uri) { - LoggerD("Enter"); + ScopeLogger(); if (0 == strcmp(view_uri, _calendar_event._uri)) { return CALENDAR_BOOK_TYPE_EVENT; } @@ -183,7 +183,7 @@ int CalendarRecord::TypeToInt(const char* view_uri) { } PlatformResult CalendarRecord::TypeToUri(const std::string& type, std::string* uri) { - LoggerD("Enter"); + ScopeLogger(); if (kCalendarTypeEvent == type) { *uri = _calendar_event._uri; } else if (kCalendarTypeTask == type) { @@ -197,7 +197,7 @@ PlatformResult CalendarRecord::TypeToUri(const std::string& type, std::string* u } PlatformResult CalendarRecord::TypeToUri(int type, std::string* uri) { - LoggerD("Enter"); + ScopeLogger(); if (CALENDAR_BOOK_TYPE_EVENT == type) { *uri = _calendar_event._uri; } else if (CALENDAR_BOOK_TYPE_TODO == type) { @@ -211,7 +211,7 @@ PlatformResult CalendarRecord::TypeToUri(int type, std::string* uri) { } PlatformResult CalendarRecord::Create(const char* view_uri, calendar_record_h* handle) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_record_create(view_uri, handle); if (CALENDAR_ERROR_NONE != ret || nullptr == handle) { return LogAndCreateResult( @@ -223,12 +223,12 @@ PlatformResult CalendarRecord::Create(const char* view_uri, calendar_record_h* h } PlatformResult CalendarRecord::CreateCalendar(calendar_record_h* handle) { - LoggerD("Enter"); + ScopeLogger(); return Create(_calendar_book._uri, handle); } PlatformResult CalendarRecord::GetById(int id, const char* view_uri, calendar_record_h* handle) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_db_get_record(view_uri, id, handle); if (CALENDAR_ERROR_NONE != ret || nullptr == handle) { return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Fail to get record with given id", @@ -240,7 +240,7 @@ PlatformResult CalendarRecord::GetById(int id, const char* view_uri, calendar_re } PlatformResult CalendarRecord::Insert(calendar_record_h rec, int* record_id) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_db_insert_record(rec, record_id); if (CALENDAR_ERROR_NONE != ret) { @@ -254,7 +254,7 @@ PlatformResult CalendarRecord::Insert(calendar_record_h rec, int* record_id) { PlatformResult CalendarRecord::AddChildRecord(calendar_record_h rec, unsigned int property, calendar_record_h child) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_record_add_child_record(rec, property, child); if (CALENDAR_ERROR_NONE != ret) { if (child) { @@ -269,7 +269,7 @@ PlatformResult CalendarRecord::AddChildRecord(calendar_record_h rec, unsigned in } void CalendarRecord::RemoveChildRecords(calendar_record_h rec, unsigned int property_id) { - LoggerD("Enter"); + ScopeLogger(); unsigned int count = 0; if (CALENDAR_ERROR_NONE != calendar_record_get_child_record_count(rec, property_id, &count)) { @@ -297,7 +297,7 @@ void CalendarRecord::RemoveChildRecords(calendar_record_h rec, unsigned int prop PlatformResult CalendarRecord::GetChildRecordCount(calendar_record_h rec, unsigned int property, bool throw_on_error, unsigned int* value) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_record_get_child_record_count(rec, property, value); if (CALENDAR_ERROR_NONE != ret) { LoggerE("Can't get child record count: %d (%s)", ret, get_error_message(ret)); @@ -311,7 +311,7 @@ PlatformResult CalendarRecord::GetChildRecordCount(calendar_record_h rec, unsign PlatformResult CalendarRecord::GetChildRecordAt(calendar_record_h rec, unsigned int property, calendar_record_h* result, int index) { - LoggerD("Enter"); + ScopeLogger(); int ret = calendar_record_get_child_record_at_p(rec, property, index, result); if (CALENDAR_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Get child record at failed.", @@ -322,7 +322,7 @@ PlatformResult CalendarRecord::GetChildRecordAt(calendar_record_h rec, unsigned } PlatformResult CalendarRecord::CalendarToJson(calendar_record_h rec, picojson::object* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); picojson::object& out = *out_ptr; if (NULL == rec) { @@ -353,7 +353,7 @@ PlatformResult CalendarRecord::CalendarToJson(calendar_record_h rec, picojson::o } PlatformResult CalendarRecord::CalendarFromJson(calendar_record_h rec, const picojson::object& in) { - LoggerD("Enter"); + ScopeLogger(); if (in.empty()) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Empty Calendar object."); } diff --git a/src/callhistory/callhistory.cc b/src/callhistory/callhistory.cc index 7352237..f531118 100644 --- a/src/callhistory/callhistory.cc +++ b/src/callhistory/callhistory.cc @@ -39,7 +39,7 @@ namespace callhistory { namespace { static void get_sim_msisdn_cb(TapiHandle* handle, int result, void* data, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); TelSimMsisdnList_t* list; std::promise* prom = reinterpret_cast*>(user_data); @@ -62,7 +62,7 @@ static void get_sim_msisdn_cb(TapiHandle* handle, int result, void* data, void* CallHistory::CallHistory(CallHistoryInstance& instance) : m_is_listener_set(false), instance_(instance), utils_(*this) { - LoggerD("Entered"); + ScopeLogger(); if (CONTACTS_ERROR_NONE == contacts_connect()) { LoggerD("Successful to connect Call history DB"); } else { @@ -71,7 +71,7 @@ CallHistory::CallHistory(CallHistoryInstance& instance) } CallHistory::~CallHistory() { - LoggerD("Entered"); + ScopeLogger(); if (m_is_listener_set) { int ret = @@ -90,7 +90,7 @@ CallHistory::~CallHistory() { } void CallHistory::FindThread(const picojson::object& args, CallHistory* call_history) { - LoggerD("Entered"); + ScopeLogger(); std::shared_ptr response{new picojson::value(picojson::object())}; @@ -233,6 +233,7 @@ void CallHistory::FindThread(const picojson::object& args, CallHistory* call_his auto find_response = [call_history, callback_id](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, find_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(&call_history->instance_, response->serialize().c_str()); @@ -242,7 +243,7 @@ void CallHistory::FindThread(const picojson::object& args, CallHistory* call_his } void CallHistory::LoadPhoneNumbers(const picojson::object& args, CallHistory* call_history) { - LoggerD("Entered"); + ScopeLogger(); CallHistory::LockedVector phone_numbers = call_history->getPhoneNumbers(); if (0 != phone_numbers.size()) { LoggerD("m_phone_numbers is already filled. Returning."); @@ -303,13 +304,13 @@ void CallHistory::LoadPhoneNumbers(const picojson::object& args, CallHistory* ca } void CallHistory::find(const picojson::object& args) { - LoggerD("Entered"); + ScopeLogger(); std::thread(LoadPhoneNumbers, args, this).detach(); std::thread(FindThread, args, this).detach(); } PlatformResult CallHistory::remove(const picojson::object& args) { - LoggerD("Entered"); + ScopeLogger(); const auto it_uid = args.find("uid"); const auto it_args_end = args.end(); @@ -328,7 +329,7 @@ PlatformResult CallHistory::remove(const picojson::object& args) { } common::PlatformResult CallHistory::removeBatch(const picojson::object& args) { - LoggerD("Entered"); + ScopeLogger(); const auto it_uid = args.find("uid"); const auto it_args_end = args.end(); @@ -362,6 +363,7 @@ common::PlatformResult CallHistory::removeBatch(const picojson::object& args) { auto remove_batch_response = [this, callback_id](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, remove_batch_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(&this->instance_, response->serialize().c_str()); @@ -374,7 +376,7 @@ common::PlatformResult CallHistory::removeBatch(const picojson::object& args) { } void CallHistory::removeAll(const picojson::object& args) { - LoggerD("Entered"); + ScopeLogger(); const double callback_id = args.find("callbackId")->second.get(); @@ -468,6 +470,7 @@ void CallHistory::removeAll(const picojson::object& args) { auto remove_all_response = [this, callback_id](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, remove_all_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(&this->instance_, response->serialize().c_str()); @@ -487,7 +490,7 @@ CallHistoryUtils& CallHistory::getUtils() { } void CallHistory::changeListenerCB(const char* view_uri, char* changes, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); CallHistory* h = static_cast(user_data); @@ -589,7 +592,7 @@ void CallHistory::changeListenerCB(const char* view_uri, char* changes, void* us } PlatformResult CallHistory::startCallHistoryChangeListener() { - LoggerD("Entered"); + ScopeLogger(); if (!m_is_listener_set) { int ret = @@ -605,7 +608,7 @@ PlatformResult CallHistory::startCallHistoryChangeListener() { } PlatformResult CallHistory::stopCallHistoryChangeListener() { - LoggerD("Entered"); + ScopeLogger(); if (m_is_listener_set) { int ret = contacts_db_remove_changed_cb_with_info(_contacts_phone_log._uri, changeListenerCB, this); @@ -619,7 +622,7 @@ PlatformResult CallHistory::stopCallHistoryChangeListener() { } PlatformResult CallHistory::setMissedDirection(int uid) { - LoggerD("Entered"); + ScopeLogger(); contacts_record_h record = nullptr; SCOPE_EXIT { diff --git a/src/callhistory/callhistory_instance.cc b/src/callhistory/callhistory_instance.cc index 64d8166..bcadb8a 100644 --- a/src/callhistory/callhistory_instance.cc +++ b/src/callhistory/callhistory_instance.cc @@ -33,7 +33,7 @@ const std::string kPrivilegeCallHistoryWrite = "http://tizen.org/privilege/callh using namespace common; CallHistoryInstance::CallHistoryInstance() : history_(*this) { - LoggerD("Entered"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -53,17 +53,18 @@ CallHistoryInstance::CallHistoryInstance() : history_(*this) { } CallHistoryInstance::~CallHistoryInstance() { + ScopeLogger(); } void CallHistoryInstance::Find(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCallHistoryRead, &out); history_.find(args.get()); ReportSuccess(out); } void CallHistoryInstance::Remove(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCallHistoryWrite, &out); PlatformResult result = history_.remove(args.get()); if (result.IsSuccess()) { @@ -74,7 +75,7 @@ void CallHistoryInstance::Remove(const picojson::value& args, picojson::object& } void CallHistoryInstance::RemoveBatch(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCallHistoryWrite, &out); PlatformResult result = history_.removeBatch(args.get()); if (result.IsSuccess()) { @@ -85,14 +86,14 @@ void CallHistoryInstance::RemoveBatch(const picojson::value& args, picojson::obj } void CallHistoryInstance::RemoveAll(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCallHistoryWrite, &out); history_.removeAll(args.get()); ReportSuccess(out); } void CallHistoryInstance::AddChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCallHistoryRead, &out); PlatformResult result = history_.startCallHistoryChangeListener(); if (result.IsSuccess()) { @@ -103,7 +104,7 @@ void CallHistoryInstance::AddChangeListener(const picojson::value& args, picojso } void CallHistoryInstance::RemoveChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeCallHistoryRead, &out); PlatformResult result = history_.stopCallHistoryChangeListener(); if (result.IsSuccess()) { @@ -114,7 +115,7 @@ void CallHistoryInstance::RemoveChangeListener(const picojson::value& args, pico } void CallHistoryInstance::SetMissedDirection(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); if (!args.contains("uid")) { LoggerD("args doesn't contain attribute 'uid'"); @@ -133,7 +134,7 @@ void CallHistoryInstance::SetMissedDirection(const picojson::value& args, picojs } void CallHistoryInstance::CallHistoryChange(picojson::object& data) { - LoggerD("Entered"); + ScopeLogger(); picojson::value event = picojson::value(data); picojson::object& obj = event.get(); obj["listenerId"] = picojson::value("CallHistoryChangeCallback"); diff --git a/src/callhistory/callhistory_utils.cc b/src/callhistory/callhistory_utils.cc index 9b67c74..536b345 100644 --- a/src/callhistory/callhistory_utils.cc +++ b/src/callhistory/callhistory_utils.cc @@ -38,10 +38,11 @@ enum CompositeTypeEnum { UNION = 0, INTERSECTION = 1, NONE = 2 }; } CallHistoryUtils::CallHistoryUtils(CallHistory& history) : history_(history) { + ScopeLogger(); } void CallHistoryUtils::parseRecordList(contacts_list_h* record_list, picojson::array& array) { - LoggerD("Entered"); + ScopeLogger(); contacts_record_h record = NULL; int total = 0; @@ -74,7 +75,7 @@ void CallHistoryUtils::parseRecordList(contacts_list_h* record_list, picojson::a } void CallHistoryUtils::parseRecord(contacts_record_h* record, picojson::object& obj) { - LoggerD("Entered"); + ScopeLogger(); int int_data; @@ -111,7 +112,7 @@ void CallHistoryUtils::parseRecord(contacts_record_h* record, picojson::object& } void CallHistoryUtils::parseLogType(contacts_phone_log_type_e log_type, picojson::object& obj) { - LoggerD("Entered"); + ScopeLogger(); picojson::value val = picojson::value(picojson::array()); picojson::array& features = val.get(); @@ -188,7 +189,7 @@ void CallHistoryUtils::parseLogType(contacts_phone_log_type_e log_type, picojson } void CallHistoryUtils::parseRemoteParties(contacts_record_h* record, picojson::object& obj) { - LoggerD("Entered"); + ScopeLogger(); char* char_data = NULL; int int_data; @@ -215,7 +216,7 @@ void CallHistoryUtils::parseRemoteParties(contacts_record_h* record, picojson::o } void CallHistoryUtils::parseCallingParty(contacts_record_h* record, picojson::object& obj) { - LoggerD("Entered"); + ScopeLogger(); int sim_count = 0; { @@ -238,7 +239,7 @@ void CallHistoryUtils::parseCallingParty(contacts_record_h* record, picojson::ob } unsigned int CallHistoryUtils::convertAttributeName(const std::string& attribute_name) { - LoggerD("Entered"); + ScopeLogger(); if (STR_RP_REMOTEPARTY == attribute_name) { return _contacts_phone_log.address; @@ -256,7 +257,7 @@ unsigned int CallHistoryUtils::convertAttributeName(const std::string& attribute } static FilterTypeEnum getFilterType(const picojson::object& filter) { - LoggerD("Entered"); + ScopeLogger(); const auto it_end = filter.end(); @@ -281,7 +282,7 @@ static FilterTypeEnum getFilterType(const picojson::object& filter) { } static CompositeTypeEnum getCompositeType(const picojson::object& filter) { - LoggerD("Entered"); + ScopeLogger(); CompositeTypeEnum type = NONE; const std::string& str_type = filter.find("type")->second.get(); @@ -294,7 +295,7 @@ static CompositeTypeEnum getCompositeType(const picojson::object& filter) { } static contacts_match_str_flag_e getMatchFlag(const std::string& match_flag) { - LoggerD("Entered"); + ScopeLogger(); if (STR_FILTER_FULLSTRING == match_flag) { return CONTACTS_MATCH_FULLSTRING; } else if (STR_FILTER_CONTAINS == match_flag) { @@ -311,7 +312,7 @@ static contacts_match_str_flag_e getMatchFlag(const std::string& match_flag) { } static std::time_t toTimeT(const std::string& value) { - LoggerD("Entered"); + ScopeLogger(); struct tm date; if (nullptr == strptime(value.c_str(), "%Y-%m-%dT%H:%M:%S", &date)) { LOGW("Couldn't convert supplied date."); @@ -320,7 +321,7 @@ static std::time_t toTimeT(const std::string& value) { } static void visitAttribute(std::stack& stack, const picojson::object filter) { - LoggerD("Entered"); + ScopeLogger(); contacts_filter_h filter_top = stack.top(); contacts_filter_h sub_filter = NULL; @@ -483,7 +484,7 @@ static void visitAttribute(std::stack& stack, const picojson: static void visitAttributeRange(std::stack& stack, const picojson::object filter) { - LoggerD("Entered"); + ScopeLogger(); unsigned int prop_id = 0; const auto it_attr_name = filter.find("attributeName"); @@ -563,7 +564,7 @@ static void visitAttributeRange(std::stack& stack, static void generateFilter(std::stack& stack, const picojson::object filter, CompositeTypeEnum type) { - LoggerD("Entered"); + ScopeLogger(); switch (getFilterType(filter)) { case FILTER_ATTRIBUTE: { visitAttribute(stack, filter); @@ -616,7 +617,7 @@ static void generateFilter(std::stack& stack, const picojson: } void CallHistoryUtils::createFilter(contacts_filter_h filter, const picojson::object filter_obj) { - LoggerD("Entered"); + ScopeLogger(); std::stack filter_stack; filter_stack.push(filter); generateFilter(filter_stack, filter_obj, CompositeTypeEnum::NONE); diff --git a/src/common/GDBus/connection.cpp b/src/common/GDBus/connection.cpp index 1cf69e8..55e64d1 100644 --- a/src/common/GDBus/connection.cpp +++ b/src/common/GDBus/connection.cpp @@ -23,7 +23,7 @@ namespace common { namespace dbus { Connection& Connection::getInstance() { - LoggerD("Entered"); + ScopeLogger(); static Connection instance; return instance; } @@ -33,11 +33,11 @@ GDBusConnection* Connection::getDBus() { } Connection::Connection() { + ScopeLogger(); m_dbus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &m_error); if (!m_dbus || m_error) { LoggerE("Could not get connection"); } - LoggerD("Connection set"); } Connection::~Connection() { diff --git a/src/common/XW_Extension.cc b/src/common/XW_Extension.cc index cee62c7..dcf87c2 100644 --- a/src/common/XW_Extension.cc +++ b/src/common/XW_Extension.cc @@ -34,7 +34,7 @@ class Extension::Detail { }; int32_t Extension::Detail::XW_Initialize(XW_Extension extension, XW_GetInterface get_interface) { - LoggerD("Enter"); + ScopeLogger(); g_extension = CreateExtension(); if (!g_extension) { LoggerE("Can't initialize extension: CreateExtension() returned NULL."); @@ -44,7 +44,7 @@ int32_t Extension::Detail::XW_Initialize(XW_Extension extension, XW_GetInterface } void Extension::Detail::OnInstanceCreated(XW_Instance xw_instance) { - LoggerD("Enter"); + ScopeLogger(); if (!g_extension) { return; } @@ -56,7 +56,7 @@ void Extension::Detail::OnInstanceCreated(XW_Instance xw_instance) { } void Extension::Detail::OnShutdown(XW_Extension) { - LoggerD("Enter"); + ScopeLogger(); delete g_extension; g_extension = nullptr; } diff --git a/src/common/converter.cc b/src/common/converter.cc index 583ce3d..48ccd60 100644 --- a/src/common/converter.cc +++ b/src/common/converter.cc @@ -22,7 +22,7 @@ namespace common { const picojson::value& FindValue(const picojson::object& in, const char* name) { - LoggerD("Enter"); + ScopeLogger(); auto it = in.find(name); if (it == in.end()) { throw common::UnknownException(std::string("Failed to find required JSON property: ") + name + diff --git a/src/common/current_application.cc b/src/common/current_application.cc index c2da8c0..eaa85be 100644 --- a/src/common/current_application.cc +++ b/src/common/current_application.cc @@ -27,28 +27,28 @@ namespace common { CurrentApplication& CurrentApplication::GetInstance() { - LoggerD("Enter"); + ScopeLogger(); static CurrentApplication current_application; return current_application; } pid_t CurrentApplication::GetProcessId() const { - LoggerD("Enter"); + ScopeLogger(); return pid_; } std::string CurrentApplication::GetApplicationId() const { - LoggerD("Enter"); + ScopeLogger(); return app_id_; } std::string CurrentApplication::GetPackageId() const { - LoggerD("Enter"); + ScopeLogger(); return package_id_; } std::string CurrentApplication::GetRoot() const { - LoggerD("Enter"); + ScopeLogger(); return root_; } @@ -57,11 +57,11 @@ CurrentApplication::CurrentApplication() app_id_(FetchApplicationId()), package_id_(FetchPackageId()), root_(FetchRoot()) { - LoggerD("Enter"); + ScopeLogger(); } std::string CurrentApplication::FetchApplicationId() const { - LoggerD("Enter"); + ScopeLogger(); std::string app_id; char* tmp_str = nullptr; @@ -79,7 +79,7 @@ std::string CurrentApplication::FetchApplicationId() const { } std::string CurrentApplication::FetchPackageId() const { - LoggerD("Enter"); + ScopeLogger(); std::string package_id; app_info_h app_info; int err = app_info_create(app_id_.c_str(), &app_info); @@ -106,7 +106,7 @@ std::string CurrentApplication::FetchPackageId() const { } std::string CurrentApplication::FetchRoot() const { - LoggerD("Enter"); + ScopeLogger(); char* path = nullptr; path = app_get_data_path(); diff --git a/src/common/extension.cc b/src/common/extension.cc index 983c73a..22f7f43 100644 --- a/src/common/extension.cc +++ b/src/common/extension.cc @@ -36,7 +36,7 @@ const XW_Internal_RuntimeInterface* g_runtime = NULL; const XW_Internal_PermissionsInterface* g_permission = NULL; bool InitializeInterfaces(XW_GetInterface get_interface) { - LoggerD("Enter"); + ScopeLogger(); static bool initialized = false; if (!initialized) { @@ -95,47 +95,47 @@ bool InitializeInterfaces(XW_GetInterface get_interface) { namespace common { Extension::Extension() : xw_extension_(g_xw_extension_) { - LoggerD("Enter"); + ScopeLogger(); } Extension::~Extension() { - LoggerD("Enter"); + ScopeLogger(); } void Extension::SetExtensionName(const char* name) { - LoggerD("Enter"); + ScopeLogger(); g_core->SetExtensionName(xw_extension_, name); } void Extension::SetJavaScriptAPI(const char* api) { - LoggerD("Enter"); + ScopeLogger(); g_core->SetJavaScriptAPI(xw_extension_, api); } void Extension::SetExtraJSEntryPoints(const char** entry_points) { - LoggerD("Enter"); + ScopeLogger(); if (g_entry_points) g_entry_points->SetExtraJSEntryPoints(xw_extension_, entry_points); } bool Extension::RegisterPermissions(const char* perm_table) { - LoggerD("Enter"); + ScopeLogger(); if (g_permission) return g_permission->RegisterPermissions(xw_extension_, perm_table); return false; } bool Extension::CheckAPIAccessControl(const char* api_name) { - LoggerD("Enter"); + ScopeLogger(); if (g_permission) return g_permission->CheckAPIAccessControl(xw_extension_, api_name); return false; } Instance* Extension::CreateInstance() { - LoggerD("Enter"); + ScopeLogger(); return NULL; } std::string Extension::GetRuntimeVariable(const char* var_name, unsigned len) { - LoggerD("Enter"); + ScopeLogger(); if (!g_runtime) return ""; std::vector res(len + 1, 0); @@ -157,7 +157,7 @@ std::string Extension::GetRuntimeVariable(const char* var_name, unsigned len) { // static void Extension::OnInstanceCreated(XW_Instance xw_instance, Instance* instance) { - LoggerD("Enter"); + ScopeLogger(); Assert(!g_core->GetInstanceData(xw_instance)); if (!instance) return; instance->xw_instance_ = xw_instance; @@ -167,7 +167,7 @@ void Extension::OnInstanceCreated(XW_Instance xw_instance, Instance* instance) { // static void Extension::OnInstanceDestroyed(XW_Instance xw_instance) { - LoggerD("Enter"); + ScopeLogger(); Instance* instance = reinterpret_cast(g_core->GetInstanceData(xw_instance)); if (!instance) return; instance->xw_instance_ = 0; @@ -176,7 +176,7 @@ void Extension::OnInstanceDestroyed(XW_Instance xw_instance) { // static void Extension::HandleMessage(XW_Instance xw_instance, const char* msg) { - LoggerD("Enter"); + ScopeLogger(); Instance* instance = reinterpret_cast(g_core->GetInstanceData(xw_instance)); if (!instance) return; instance->HandleMessage(msg); @@ -184,7 +184,7 @@ void Extension::HandleMessage(XW_Instance xw_instance, const char* msg) { // static void Extension::HandleSyncMessage(XW_Instance xw_instance, const char* msg) { - LoggerD("Enter"); + ScopeLogger(); Instance* instance = reinterpret_cast(g_core->GetInstanceData(xw_instance)); if (!instance) return; instance->HandleSyncMessage(msg); @@ -195,7 +195,7 @@ int32_t Extension::XW_Initialize(XW_Extension extension, XW_GetInterface get_int XW_Initialize_Func initialize, XW_CreatedInstanceCallback created_instance, XW_ShutdownCallback shutdown) { - LoggerD("Enter"); + ScopeLogger(); Assert(extension); if (!InitializeInterfaces(get_interface)) { @@ -221,18 +221,18 @@ int32_t Extension::XW_Initialize(XW_Extension extension, XW_GetInterface get_int std::unordered_set Instance::all_instances_; Instance::Instance() : xw_instance_(0) { - LoggerD("Enter"); + ScopeLogger(); { all_instances_.insert(this); } } Instance::~Instance() { - LoggerD("Enter"); + ScopeLogger(); { all_instances_.erase(this); } Assert(xw_instance_ == 0); } void Instance::PostMessage(Instance* that, const char* msg) { - LoggerD("Enter"); + ScopeLogger(); if (that && all_instances_.end() != all_instances_.find(that)) { that->PostMessage(msg); } else { @@ -241,7 +241,7 @@ void Instance::PostMessage(Instance* that, const char* msg) { } void Instance::PostMessage(const char* msg) { - LoggerD("Enter"); + ScopeLogger(); if (!xw_instance_) { LoggerE( "Ignoring PostMessage() in the constructor or after the " @@ -252,7 +252,7 @@ void Instance::PostMessage(const char* msg) { } void Instance::SendSyncReply(const char* reply) { - LoggerD("Enter"); + ScopeLogger(); if (!xw_instance_) { LoggerE( "Ignoring SendSyncReply() in the constructor or after the " @@ -263,60 +263,60 @@ void Instance::SendSyncReply(const char* reply) { } ParsedInstance::ParsedInstance() { - LoggerD("Enter"); + ScopeLogger(); } ParsedInstance::~ParsedInstance() { - LoggerD("Enter"); + ScopeLogger(); } void ParsedInstance::RegisterHandler(const std::string& name, const NativeHandler& func) { - LoggerD("Enter"); + ScopeLogger(); handler_map_.insert(std::make_pair(name, func)); } void ParsedInstance::RegisterSyncHandler(const std::string& name, const NativeHandler& func) { - LoggerD("Enter"); + ScopeLogger(); handler_map_.insert(std::make_pair("#SYNC#" + name, func)); } void ParsedInstance::ReportSuccess(picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); tools::ReportSuccess(out); } void ParsedInstance::ReportSuccess(const picojson::value& result, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); tools::ReportSuccess(result, out); } void ParsedInstance::ReportError(picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); tools::ReportError(out); } void ParsedInstance::ReportError(const PlatformException& ex, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); tools::ReportError(ex, out); } void ParsedInstance::ReportError(const PlatformResult& error, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); tools::ReportError(error, out); } void ParsedInstance::HandleMessage(const char* msg) { - LoggerD("Enter"); + ScopeLogger(); HandleMessage(msg, false); } void ParsedInstance::HandleSyncMessage(const char* msg) { - LoggerD("Enter"); + ScopeLogger(); HandleMessage(msg, true); } void ParsedInstance::HandleMessage(const char* msg, bool is_sync) { - LoggerD("Enter"); + ScopeLogger(); try { picojson::value value; std::string err; @@ -360,7 +360,7 @@ void ParsedInstance::HandleMessage(const char* msg, bool is_sync) { } void ParsedInstance::HandleException(const PlatformException& ex) { - LoggerD("Enter"); + ScopeLogger(); LoggerE("Exception: %s", ex.message().c_str()); picojson::value result = picojson::value(picojson::object()); ReportError(ex, result.get()); diff --git a/src/common/filesystem/filesystem_provider.cc b/src/common/filesystem/filesystem_provider.cc index 882f3f9..140b749 100644 --- a/src/common/filesystem/filesystem_provider.cc +++ b/src/common/filesystem/filesystem_provider.cc @@ -21,58 +21,58 @@ namespace common { IFilesystemProvider::IFilesystemProvider() { - LoggerD("enter"); + ScopeLogger(); } IFilesystemProvider::~IFilesystemProvider() { - LoggerD("enter"); + ScopeLogger(); } FilesystemProvider::FilesystemProvider() : provider_(FilesystemProviderDeviced::Create()) { } FilesystemProvider& FilesystemProvider::Create() { - LoggerD("Entered"); + ScopeLogger(); static FilesystemProvider instance; return instance; } FilesystemProvider::~FilesystemProvider() { - LoggerD("Entered"); + ScopeLogger(); } void FilesystemProvider::RegisterDeviceChangeState(DeviceChangeStateFun callback) { - LoggerD("Entered"); + ScopeLogger(); provider_.RegisterDeviceChangeState(callback); } void FilesystemProvider::UnregisterDeviceChangeState() { - LoggerD("Entered"); + ScopeLogger(); provider_.UnregisterDeviceChangeState(); } Storages FilesystemProvider::GetStorages() { - LoggerD("Entered"); + ScopeLogger(); return provider_.GetStorages(); } VirtualRoots FilesystemProvider::GetVirtualPaths() { - LoggerD("Entered"); + ScopeLogger(); return provider_.GetVirtualPaths(); } VirtualStorages FilesystemProvider::GetAllStorages() { - LoggerD("Entered"); + ScopeLogger(); return provider_.GetAllStorages(); } std::string FilesystemProvider::GetRealPath(const std::string& path_or_uri) { - LoggerD("Entered"); + ScopeLogger(); return FilesystemProviderStorage::Create().GetRealPath(path_or_uri); } std::string FilesystemProvider::GetVirtualPath(const std::string& real_path) const { - LoggerD("Entered"); + ScopeLogger(); return FilesystemProviderStorage::Create().GetVirtualPath(real_path); } diff --git a/src/common/filesystem/filesystem_provider_deviced.cc b/src/common/filesystem/filesystem_provider_deviced.cc index 19e7a12..2ce1ab4 100644 --- a/src/common/filesystem/filesystem_provider_deviced.cc +++ b/src/common/filesystem/filesystem_provider_deviced.cc @@ -93,7 +93,7 @@ struct UsbListElem { }; FilesystemProviderDeviced::~FilesystemProviderDeviced() { - LoggerD("Entered"); + ScopeLogger(); UnregisterDeviceChangeState(); } @@ -104,7 +104,7 @@ FilesystemProviderDeviced::FilesystemProviderDeviced() block_signal_subscribe_id_(0), virtual_roots_provider_(FilesystemProviderStorage::Create()), is_initialized_(false) { - LoggerD("Entered"); + ScopeLogger(); GError* error = nullptr; @@ -122,7 +122,7 @@ FilesystemProviderDeviced::FilesystemProviderDeviced() } FilesystemProviderDeviced& FilesystemProviderDeviced::Create() { - LoggerD("Entered"); + ScopeLogger(); static FilesystemProviderDeviced instance; @@ -134,7 +134,7 @@ void FilesystemProviderDeviced::BlockSignalProxy(GDBusConnection* connection, const gchar* interface_name, const gchar* signal_name, GVariant* parameters, gpointer user_data) { - LoggerD("Entered"); + ScopeLogger(); FilesystemProviderDeviced* instance = static_cast(user_data); DeviceListElem elem; @@ -145,7 +145,7 @@ void FilesystemProviderDeviced::BlockSignalProxy(GDBusConnection* connection, } void FilesystemProviderDeviced::BlockSignalCallback(DeviceListElem elem) { - LoggerD("Entered"); + ScopeLogger(); StorageState previous_state = StorageState::kUnmounted; auto it = previous_device_state_map_.find(elem.syspath); if (it == previous_device_state_map_.end()) { @@ -161,7 +161,7 @@ void FilesystemProviderDeviced::BlockSignalCallback(DeviceListElem elem) { } void FilesystemProviderDeviced::RegisterDeviceChangeState(DeviceChangeStateFun _callback) { - LoggerD("Entered"); + ScopeLogger(); if (!is_initialized_) { LoggerE("DeviceD Core api not initialized"); @@ -178,7 +178,7 @@ void FilesystemProviderDeviced::RegisterDeviceChangeState(DeviceChangeStateFun _ } void FilesystemProviderDeviced::UnregisterDeviceChangeState() { - LoggerD("Entered"); + ScopeLogger(); if (!is_initialized_) { LoggerE("DeviceD Core api not initialized"); @@ -193,7 +193,7 @@ void FilesystemProviderDeviced::UnregisterDeviceChangeState() { } std::shared_ptr FilesystemProviderDeviced::GetStorage(const DeviceListElem& elem) { - LoggerD("Entered"); + ScopeLogger(); return std::make_shared(GetIdFromUUID(elem.fs_uuid_enc), (elem.block_type ? StorageType::kMmc : StorageType::kUsbDevice), (elem.state ? StorageState::kMounted : StorageState::kUnmounted), @@ -201,7 +201,7 @@ std::shared_ptr FilesystemProviderDeviced::GetStorage(const DeviceListE } std::string FilesystemProviderDeviced::GetNameFromPath(const char* const char_path) { - LoggerD("Entered"); + ScopeLogger(); std::string path = char_path; std::string name = "removable_"; std::size_t last_slash_pos = path.find_last_of("/"); @@ -215,12 +215,12 @@ std::string FilesystemProviderDeviced::GetNameFromPath(const char* const char_pa } int FilesystemProviderDeviced::GetIdFromUUID(const char* const char_uuid) { - LoggerD("Entered"); + ScopeLogger(); return (int)std::hash()(std::string(char_uuid)); } Storages FilesystemProviderDeviced::GetStorages() { - LoggerD("Entered"); + ScopeLogger(); if (!is_initialized_) { LoggerE("DeviceD Core api not initialized"); return Storages(); @@ -249,7 +249,7 @@ Storages FilesystemProviderDeviced::GetStorages() { } Storages FilesystemProviderDeviced::GetStoragesFromGVariant(GVariant* variant) { - LoggerD("Entered"); + ScopeLogger(); Storages storages; GVariantIter* iter; @@ -281,7 +281,7 @@ Storages FilesystemProviderDeviced::GetStoragesFromGVariant(GVariant* variant) { } VirtualRoots FilesystemProviderDeviced::GetVirtualPaths() { - LoggerD("Entered"); + ScopeLogger(); if (!is_initialized_) { LoggerE("DeviceD Core api not initialized"); @@ -292,7 +292,7 @@ VirtualRoots FilesystemProviderDeviced::GetVirtualPaths() { } VirtualStorages FilesystemProviderDeviced::GetAllStorages() { - LoggerD("Entered"); + ScopeLogger(); if (!is_initialized_) { LoggerE("DeviceD Core api not initialized"); diff --git a/src/common/filesystem/filesystem_provider_storage.cc b/src/common/filesystem/filesystem_provider_storage.cc index a744dc9..a82e630 100644 --- a/src/common/filesystem/filesystem_provider_storage.cc +++ b/src/common/filesystem/filesystem_provider_storage.cc @@ -51,7 +51,7 @@ const std::string kFileUriPrefix = "file://"; namespace common { StorageState TranslateCoreStorageState(storage_state_e coreStorageState) { - LoggerD("Entered"); + ScopeLogger(); StorageState state = StorageState::kUnknown; if (coreStorageState == STORAGE_STATE_REMOVED) { state = StorageState::kUnmounted; @@ -66,7 +66,7 @@ StorageState TranslateCoreStorageState(storage_state_e coreStorageState) { } void OnStorageChange(int storage_id, storage_state_e state, void* user_data) { - LoggerD("Entered, id: %d", storage_id); + ScopeLogger("id: %d", storage_id); FilesystemProviderStorage* provider = static_cast(user_data); for (auto& storage : provider->GetStorages()) { @@ -83,7 +83,7 @@ void OnStorageChange(int storage_id, storage_state_e state, void* user_data) { bool OnForeachStorage(int storage_id, storage_type_e type, storage_state_e state, const char* path, void* user_data) { - LoggerD("Entered, id: %d", storage_id); + ScopeLogger("id: %d", storage_id); FilesystemProviderStorage* provider = static_cast(user_data); // handling only internal storages (external are handled with deviced api) @@ -104,7 +104,7 @@ DeviceChangeStateFun FilesystemProviderStorage::GetListener() { } FilesystemProviderStorage::FilesystemProviderStorage() { - LoggerD("Entered"); + ScopeLogger(); int err = storage_foreach_device_supported(OnForeachStorage, this); if (err != STORAGE_ERROR_NONE) { LoggerE("Unknown Error on getting storage paths"); @@ -112,13 +112,13 @@ FilesystemProviderStorage::FilesystemProviderStorage() { } FilesystemProviderStorage& FilesystemProviderStorage::Create() { - LoggerD("Entered"); + ScopeLogger(); static FilesystemProviderStorage fs; return fs; } FilesystemProviderStorage::~FilesystemProviderStorage() { - LoggerD("Entered"); + ScopeLogger(); } void FilesystemProviderStorage::FillVirtualPaths(int storage_id) { @@ -143,27 +143,27 @@ void FilesystemProviderStorage::FillVirtualPaths(int storage_id) { } void FilesystemProviderStorage::RegisterDeviceChangeState(DeviceChangeStateFun callback) { - LoggerD("Entered"); + ScopeLogger(); listener_ = callback; } void FilesystemProviderStorage::UnregisterDeviceChangeState() { - LoggerD("Entered"); + ScopeLogger(); listener_ = nullptr; } Storages FilesystemProviderStorage::GetStorages() { - LoggerD("Entered"); + ScopeLogger(); return storages_; } VirtualRoots FilesystemProviderStorage::GetVirtualPaths() { - LoggerD("Entered"); + ScopeLogger(); return virtual_paths_; } std::string FilesystemProviderStorage::GetRealPath(const std::string& path_or_uri) { - LoggerD("Enter"); + ScopeLogger(); std::string realpath; std::size_t pos = path_or_uri.find(kFileUriPrefix); if (pos != std::string::npos) { @@ -187,7 +187,7 @@ std::string FilesystemProviderStorage::GetRealPath(const std::string& path_or_ur } std::string FilesystemProviderStorage::GetVirtualPath(const std::string& real_path) const { - LoggerD("Enter"); + ScopeLogger(); for (const auto& kv : virtual_paths_) { if (0 == real_path.compare(0, kv.path_.size(), kv.path_)) { return std::string(real_path).replace(0, kv.path_.size(), kv.name_); @@ -197,7 +197,7 @@ std::string FilesystemProviderStorage::GetVirtualPath(const std::string& real_pa } VirtualStorages FilesystemProviderStorage::GetAllStorages() { - LoggerD("Entered"); + ScopeLogger(); VirtualStorages vs; for (auto storage : storages_) { vs.push_back(storage); diff --git a/src/common/filesystem/filesystem_storage.cc b/src/common/filesystem/filesystem_storage.cc index a776e69..0efc186 100644 --- a/src/common/filesystem/filesystem_storage.cc +++ b/src/common/filesystem/filesystem_storage.cc @@ -23,13 +23,13 @@ namespace common { VirtualRoot::VirtualRoot(std::string const& name, std::string const& path, StorageType type, StorageState state) : name_(name), path_(path), type_(type), state_(state) { - LoggerD("Entered"); + ScopeLogger(); } Storage::Storage(int id, StorageType type, StorageState state, std::string const& path, std::string const& name) : VirtualRoot(name, path, type, state), id_(id) { - LoggerD("Enter"); + ScopeLogger(); if (name_ == "") { switch (type) { case StorageType::kInternal: @@ -50,7 +50,7 @@ Storage::Storage(int id, StorageType type, StorageState state, std::string const } picojson::value VirtualRoot::ToJson() const { - LoggerD("Entered"); + ScopeLogger(); picojson::value v{picojson::object{}}; picojson::object& obj = v.get(); @@ -63,7 +63,7 @@ picojson::value VirtualRoot::ToJson() const { } picojson::value Storage::ToJson() const { - LoggerD("Entered"); + ScopeLogger(); picojson::value value = VirtualRoot::ToJson(); picojson::object& obj = value.get(); obj["storage_id"] = picojson::value(static_cast(id_)); @@ -71,12 +71,12 @@ picojson::value Storage::ToJson() const { } Storage::Storage(Storage const& other) : VirtualRoot(other) { - LoggerD("Entered"); + ScopeLogger(); this->id_ = other.id_; } VirtualRoot::VirtualRoot(VirtualRoot const& other) { - LoggerD("Entered"); + ScopeLogger(); this->path_ = other.path_; this->name_ = other.name_; this->state_ = other.state_; @@ -84,7 +84,7 @@ VirtualRoot::VirtualRoot(VirtualRoot const& other) { } std::string VirtualRoot::ToString(StorageType type) { - LoggerD("Entered"); + ScopeLogger(); switch (type) { case StorageType::kInternal: return "INTERNAL"; @@ -99,7 +99,7 @@ std::string VirtualRoot::ToString(StorageType type) { } std::string VirtualRoot::ToString(StorageState state) { - LoggerD("Entered"); + ScopeLogger(); switch (state) { case StorageState::kUnmounted: return "REMOVED"; diff --git a/src/common/filter-utils.cc b/src/common/filter-utils.cc index 9bc7441..c263ce3 100644 --- a/src/common/filter-utils.cc +++ b/src/common/filter-utils.cc @@ -23,7 +23,7 @@ namespace common { PlatformResult AttributeMatchFlagFromString(const std::string &str, AttributeMatchFlag *filter_match_flag) { - LoggerD("Enter"); + ScopeLogger(); if (str == "EXACTLY") { *filter_match_flag = AttributeMatchFlag::kExactly; } else if (str == "FULLSTRING") { @@ -46,7 +46,7 @@ PlatformResult AttributeMatchFlagFromString(const std::string &str, PlatformResult CompositeFilterTypeFromString(const std::string &str, CompositeFilterType *comp_filter_type) { - LoggerD("Enter"); + ScopeLogger(); if (str == "UNION") { *comp_filter_type = CompositeFilterType::kUnion; } else if (str == "INTERSECTION") { @@ -61,27 +61,27 @@ PlatformResult CompositeFilterTypeFromString(const std::string &str, } void FilterVisitor::SetOnAttributeFilter(const AttributeFilterOnVisit &func) { - LoggerD("Enter"); + ScopeLogger(); m_attributeFilterOnVisit = func; } void FilterVisitor::SetOnAttributeRangeFilter(const AttributeRangeFilterOnVisit &func) { - LoggerD("Enter"); + ScopeLogger(); m_attributeRangeFilterOnVisit = func; } void FilterVisitor::SetOnCompositeFilterBegin(const CompositeFilterOnBegin &func) { - LoggerD("Enter"); + ScopeLogger(); m_compositeFilterOnBegin = func; } void FilterVisitor::SetOnCompositeFilterEnd(const CompositeFilterOnEnd &func) { - LoggerD("Enter"); + ScopeLogger(); m_compositeFilterOnEnd = func; } PlatformResult FilterVisitor::Visit(const picojson::object &filter) { - LoggerD("Enter"); + ScopeLogger(); const std::string &filterType = FromJson(filter, "filterType"); if (filterType == "AttributeFilter") { PlatformResult status = VisitAttributeFilter(filter); @@ -101,7 +101,7 @@ PlatformResult FilterVisitor::Visit(const picojson::object &filter) { } PlatformResult FilterVisitor::VisitAttributeFilter(const picojson::object &filter) { - LoggerD("Enter"); + ScopeLogger(); const std::string &attribute_name = FromJson(filter, "attributeName"); AttributeMatchFlag match_flag; @@ -120,7 +120,7 @@ PlatformResult FilterVisitor::VisitAttributeFilter(const picojson::object &filte } PlatformResult FilterVisitor::VisitAttributeRangeFilter(const picojson::object &filter) { - LoggerD("Enter"); + ScopeLogger(); const std::string &attributeName = FromJson(filter, "attributeName"); const picojson::value &initialValue = FindValue(filter, "initialValue"); const picojson::value &endValue = FindValue(filter, "endValue"); @@ -134,7 +134,7 @@ PlatformResult FilterVisitor::VisitAttributeRangeFilter(const picojson::object & } PlatformResult FilterVisitor::VisitCompositeFilter(const picojson::object &filter) { - LoggerD("Enter"); + ScopeLogger(); CompositeFilterType filter_type; PlatformResult status = CompositeFilterTypeFromString(FromJson(filter, "type"), &filter_type); diff --git a/src/common/platform_result.cc b/src/common/platform_result.cc index ec3a50d..554a6d0 100644 --- a/src/common/platform_result.cc +++ b/src/common/platform_result.cc @@ -21,7 +21,7 @@ namespace common { PlatformResult::PlatformResult(const ErrorCode& error_code, const std::string& message) : error_code_(error_code), message_(message) { - LoggerD("Enter"); + ScopeLogger(); if (ErrorCode::NO_ERROR != error_code) { LoggerE("PlatformResult: %d, message: %s", error_code, message.c_str()); @@ -29,7 +29,7 @@ PlatformResult::PlatformResult(const ErrorCode& error_code, const std::string& m } picojson::value PlatformResult::ToJSON() const { - LoggerD("Enter"); + ScopeLogger(); picojson::value::object obj; obj["code"] = picojson::value(static_cast(error_code_)); if (!message_.empty()) obj["message"] = picojson::value(message_); diff --git a/src/common/tools.cc b/src/common/tools.cc index 588663f..6aa2896 100644 --- a/src/common/tools.cc +++ b/src/common/tools.cc @@ -40,12 +40,12 @@ namespace common { namespace tools { void ReportSuccess(picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); out.insert(std::make_pair("status", picojson::value("success"))); } void ReportSuccess(const picojson::value& result, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); out.insert(std::make_pair("status", picojson::value("success"))); out.insert(std::make_pair("result", result)); } @@ -74,7 +74,7 @@ namespace { class AccessControlImpl { public: AccessControlImpl() : initialized_(false) { - LoggerD("Privilege access checked using DB."); + ScopeLogger("Privilege access checked using DB."); const char* kWrtDBPath = "/opt/dbspace/.wrt.db"; sqlite3* db = nullptr; @@ -118,7 +118,7 @@ class AccessControlImpl { } bool CheckAccess(const std::vector& privileges) { - LoggerD("Enter"); + ScopeLogger(); if (!initialized_) { return false; } @@ -150,7 +150,7 @@ class AccessControlImpl { } bool CheckAccess(const std::vector& privileges) { - LoggerD("Enter"); + ScopeLogger(); return true; } @@ -161,7 +161,7 @@ class AccessControlImpl { class AccessControlImpl { public: AccessControlImpl() : cynara_(nullptr) { - LoggerD("Privilege access checked using Cynara."); + ScopeLogger("Privilege access checked using Cynara."); char* smack_label = nullptr; int len = smack_new_label_from_self(&smack_label); @@ -267,7 +267,7 @@ PlatformResult CheckAccess(const std::string& privilege) { } PlatformResult CheckAccess(const std::vector& privileges) { - LoggerD("Enter"); + ScopeLogger(); // Local cache of mapped privilege strings. This routine can be called many times, especially // during application launch, generating a high overhead of retrieving mapped privileges from @@ -339,7 +339,7 @@ PlatformResult CheckAccess(const std::vector& privileges) { } PlatformResult GetPkgApiVersion(std::string* api_version) { - LoggerD("Entered"); + ScopeLogger(); // Local cache of API version string. This can be expensive to retrieve from // underlying databases and this routine can be called many times during @@ -420,7 +420,7 @@ std::vector SplitString(const std::string& str, const std::string& } bool IsAppVersionEarlierThan(const std::string& ver) { - LoggerD("Enter"); + ScopeLogger(); std::string app_ver; auto res = GetPkgApiVersion(&app_ver); if (!res) { @@ -480,7 +480,7 @@ char* BinToHex(const unsigned char* bin, int size, char* hex, int hex_size) { } bool IsPathValid(const std::string& path) { - LoggerD("Enter"); + ScopeLogger(); /* * Directory dot-referencing is not allowed @@ -491,7 +491,7 @@ bool IsPathValid(const std::string& path) { } PlatformResult CheckFileStatus(const std::string& path) { - LoggerD("Enter"); + ScopeLogger(); struct stat buf; @@ -521,7 +521,7 @@ PlatformResult CheckFileStatus(const std::string& path) { } PlatformResult CheckFileAvailability(const std::string& path) { - LoggerD("Enter"); + ScopeLogger(); if (!IsPathValid(path)) { return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid path: " + path); diff --git a/src/contact/addressbook.cc b/src/contact/addressbook.cc index 755a857..447b171 100644 --- a/src/contact/addressbook.cc +++ b/src/contact/addressbook.cc @@ -53,7 +53,7 @@ inline bool IsUnified(long id) { } // anonymous namespace PlatformResult AddressBookGet(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -79,7 +79,7 @@ PlatformResult AddressBookGet(const JsonObject& args, JsonObject& out) { } PlatformResult AddressBookAdd(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -135,7 +135,7 @@ PlatformResult AddressBookAdd(const JsonObject& args, JsonObject& out) { } PlatformResult AddressBookUpdate(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -177,7 +177,7 @@ PlatformResult AddressBookUpdate(const JsonObject& args, JsonObject& out) { } PlatformResult AddressBookRemove(const JsonObject& args, JsonObject&) { - LoggerE("entered"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -198,7 +198,7 @@ PlatformResult AddressBookRemove(const JsonObject& args, JsonObject&) { } PlatformResult AddressBookAddBatch(const JsonObject& args, JsonArray& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -275,7 +275,7 @@ PlatformResult AddressBookAddBatch(const JsonObject& args, JsonArray& out) { } PlatformResult AddressBookUpdateBatch(const JsonObject& args, JsonArray& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -333,7 +333,7 @@ PlatformResult AddressBookUpdateBatch(const JsonObject& args, JsonArray& out) { } PlatformResult AddressBookRemoveBatch(const JsonObject& args) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -358,7 +358,7 @@ PlatformResult AddressBookRemoveBatch(const JsonObject& args) { } PlatformResult AddressBookFind(const JsonObject& args, JsonArray& array) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (!status) return status; @@ -387,7 +387,7 @@ PlatformResult AddressBookFind(const JsonObject& args, JsonArray& array) { } PlatformResult AddressBookAddGroup(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -424,7 +424,7 @@ PlatformResult AddressBookAddGroup(const JsonObject& args, JsonObject& out) { } PlatformResult AddressBookGetGroup(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -460,7 +460,7 @@ PlatformResult AddressBookGetGroup(const JsonObject& args, JsonObject& out) { } PlatformResult AddressBookUpdateGroup(const JsonObject& args, JsonObject&) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -509,7 +509,7 @@ PlatformResult AddressBookUpdateGroup(const JsonObject& args, JsonObject&) { } PlatformResult AddressBookRemoveGroup(const JsonObject& args, JsonObject&) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -549,7 +549,7 @@ PlatformResult AddressBookRemoveGroup(const JsonObject& args, JsonObject&) { } PlatformResult AddressBookGetGroups(const JsonObject& args, JsonArray& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -640,7 +640,7 @@ PlatformResult AddressBookGetGroups(const JsonObject& args, JsonArray& out) { namespace { void AddressBookListenerCallback(const char* view_uri, void* user_data) { - LoggerD("entered"); + ScopeLogger(); (void)view_uri; PlatformResult status = ContactUtil::CheckDBConnection(); @@ -787,7 +787,7 @@ void AddressBookListenerCallback(const char* view_uri, void* user_data) { PlatformResult AddressBookStartListening(ContactInstance& instance, const JsonObject&, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; int current_state = 0; @@ -816,7 +816,7 @@ PlatformResult AddressBookStartListening(ContactInstance& instance, const JsonOb } PlatformResult AddressBookStopListening(ContactInstance& instance) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; diff --git a/src/contact/contact_instance.cc b/src/contact/contact_instance.cc index 252bef0..0b58bd8 100644 --- a/src/contact/contact_instance.cc +++ b/src/contact/contact_instance.cc @@ -37,6 +37,7 @@ const std::string kPrivilegeContactWrite = "http://tizen.org/privilege/contact.w using namespace common; ContactInstance::ContactInstance() : current_state_(0), is_listening_(false) { + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -87,6 +88,7 @@ ContactInstance::ContactInstance() : current_state_(0), is_listening_(false) { } ContactInstance::~ContactInstance() { + ScopeLogger(); if (is_listening_) { AddressBook::AddressBookStopListening(*this); set_is_listening(false); @@ -94,6 +96,7 @@ ContactInstance::~ContactInstance() { } void ContactInstance::AddressBookGet(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = @@ -105,6 +108,7 @@ void ContactInstance::AddressBookGet(const JsonValue& args, JsonObject& out) { } void ContactInstance::AddressBookAdd(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = @@ -116,12 +120,13 @@ void ContactInstance::AddressBookAdd(const JsonValue& args, JsonObject& out) { } void ContactInstance::AddressBookAddBatch(const JsonValue& args, JsonObject& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); JsonValue result = JsonValue(JsonArray()); PlatformResult status = AddressBook::AddressBookAddBatch(common::JsonCast(args), result.get()); @@ -132,6 +137,7 @@ void ContactInstance::AddressBookAddBatch(const JsonValue& args, JsonObject& out }; auto get_response = [this, callback_id](const std::shared_ptr& response) { + ScopeLogger("Entered into asynchronous function, get_response"); JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -143,12 +149,13 @@ void ContactInstance::AddressBookAddBatch(const JsonValue& args, JsonObject& out } void ContactInstance::AddressBookRemoveBatch(const JsonValue& args, JsonObject& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); PlatformResult status = AddressBook::AddressBookRemoveBatch(common::JsonCast(args)); if (status.IsSuccess()) @@ -158,6 +165,7 @@ void ContactInstance::AddressBookRemoveBatch(const JsonValue& args, JsonObject& }; auto get_response = [this, callback_id](const std::shared_ptr& response) { + ScopeLogger("Entered into asynchronous function, get_response"); JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -169,12 +177,13 @@ void ContactInstance::AddressBookRemoveBatch(const JsonValue& args, JsonObject& } void ContactInstance::AddressBookUpdateBatch(const JsonValue& args, JsonObject& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); JsonValue result = JsonValue(JsonArray()); PlatformResult status = AddressBook::AddressBookUpdateBatch(common::JsonCast(args), result.get()); @@ -185,6 +194,7 @@ void ContactInstance::AddressBookUpdateBatch(const JsonValue& args, JsonObject& }; auto get_response = [this, callback_id](const std::shared_ptr& response) { + ScopeLogger("Entered into asynchronous function, get_response"); JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -196,6 +206,7 @@ void ContactInstance::AddressBookUpdateBatch(const JsonValue& args, JsonObject& } void ContactInstance::AddressBookUpdate(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = @@ -207,6 +218,7 @@ void ContactInstance::AddressBookUpdate(const JsonValue& args, JsonObject& out) } void ContactInstance::AddressBookRemove(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = @@ -218,11 +230,12 @@ void ContactInstance::AddressBookRemove(const JsonValue& args, JsonObject& out) } void ContactInstance::AddressBookFind(const JsonValue& args, JsonObject& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); JsonValue result = JsonValue(JsonArray()); PlatformResult status = AddressBook::AddressBookFind(JsonCast(args), result.get()); @@ -233,6 +246,7 @@ void ContactInstance::AddressBookFind(const JsonValue& args, JsonObject& out) { }; auto get_response = [this, callback_id](const std::shared_ptr& response) { + ScopeLogger("Entered into asynchronous function, get_response"); JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -244,6 +258,7 @@ void ContactInstance::AddressBookFind(const JsonValue& args, JsonObject& out) { } void ContactInstance::AddressBookAddGroup(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = @@ -255,6 +270,7 @@ void ContactInstance::AddressBookAddGroup(const JsonValue& args, JsonObject& out } void ContactInstance::AddressBookGetGroup(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = @@ -266,6 +282,7 @@ void ContactInstance::AddressBookGetGroup(const JsonValue& args, JsonObject& out } void ContactInstance::AddressBookUpdateGroup(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = AddressBook::AddressBookUpdateGroup(common::JsonCast(args), @@ -277,6 +294,7 @@ void ContactInstance::AddressBookUpdateGroup(const JsonValue& args, JsonObject& } void ContactInstance::AddressBookRemoveGroup(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = AddressBook::AddressBookRemoveGroup(common::JsonCast(args), @@ -288,6 +306,7 @@ void ContactInstance::AddressBookRemoveGroup(const JsonValue& args, JsonObject& } void ContactInstance::AddressBookGetGroups(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonArray{}}; PlatformResult status = @@ -299,11 +318,13 @@ void ContactInstance::AddressBookGetGroups(const JsonValue& args, JsonObject& ou } void ContactInstance::ContactManagerGetAddressBooks(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); JsonValue result = JsonValue(JsonArray()); PlatformResult status = ContactManager::ContactManagerGetAddressBooks( common::JsonCast(args), result.get()); @@ -315,6 +336,7 @@ void ContactInstance::ContactManagerGetAddressBooks(const JsonValue& args, JsonO }; auto get_response = [this, callback_id](const std::shared_ptr& response) { + ScopeLogger("Entered into asynchronous function, get_response"); JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -326,6 +348,7 @@ void ContactInstance::ContactManagerGetAddressBooks(const JsonValue& args, JsonO } void ContactInstance::ContactManagerGetAddressBook(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerGetAddressBook( @@ -337,6 +360,7 @@ void ContactInstance::ContactManagerGetAddressBook(const JsonValue& args, JsonOb } void ContactInstance::ContactManagerAddAddressBook(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerAddAddressBook( @@ -348,6 +372,7 @@ void ContactInstance::ContactManagerAddAddressBook(const JsonValue& args, JsonOb } void ContactInstance::ContactManagerRemoveAddressBook(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerRemoveAddressBook( @@ -359,6 +384,7 @@ void ContactInstance::ContactManagerRemoveAddressBook(const JsonValue& args, Jso } void ContactInstance::AddressBookStartListening(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = AddressBook::AddressBookStartListening( @@ -370,6 +396,7 @@ void ContactInstance::AddressBookStartListening(const JsonValue& args, JsonObjec } void ContactInstance::AddressBookStopListening(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = AddressBook::AddressBookStopListening(*this); @@ -380,6 +407,7 @@ void ContactInstance::AddressBookStopListening(const JsonValue& args, JsonObject } void ContactInstance::ContactManagerGet(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = @@ -391,6 +419,7 @@ void ContactInstance::ContactManagerGet(const JsonValue& args, JsonObject& out) } void ContactInstance::ContactManagerUpdate(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerUpdate(common::JsonCast(args), @@ -402,12 +431,13 @@ void ContactInstance::ContactManagerUpdate(const JsonValue& args, JsonObject& ou } void ContactInstance::ContactManagerUpdateBatch(const JsonValue& args, JsonObject& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); PlatformResult status = ContactManager::ContactManagerUpdateBatch(common::JsonCast(args)); @@ -418,6 +448,7 @@ void ContactInstance::ContactManagerUpdateBatch(const JsonValue& args, JsonObjec }; auto get_response = [this, callback_id](const std::shared_ptr& response) { + ScopeLogger("Entered into asynchronous function, get_response"); JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -429,6 +460,7 @@ void ContactInstance::ContactManagerUpdateBatch(const JsonValue& args, JsonObjec } void ContactInstance::ContactManagerRemove(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerRemove(common::JsonCast(args), @@ -440,12 +472,13 @@ void ContactInstance::ContactManagerRemove(const JsonValue& args, JsonObject& ou } void ContactInstance::ContactManagerRemoveBatch(const JsonValue& args, JsonObject& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); PlatformResult status = ContactManager::ContactManagerRemoveBatch(common::JsonCast(args)); @@ -456,6 +489,7 @@ void ContactInstance::ContactManagerRemoveBatch(const JsonValue& args, JsonObjec }; auto get_response = [this, callback_id](const std::shared_ptr& response) { + ScopeLogger("Entered into asynchronous function, get_response"); JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -467,10 +501,12 @@ void ContactInstance::ContactManagerRemoveBatch(const JsonValue& args, JsonObjec } void ContactInstance::ContactManagerFind(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); const double callback_id = args.get("callbackId").get(); auto get = [this, args](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); JsonValue result = JsonValue(JsonArray()); PlatformResult status = ContactManager::ContactManagerFind(common::JsonCast(args), @@ -483,6 +519,7 @@ void ContactInstance::ContactManagerFind(const JsonValue& args, JsonObject& out) }; auto get_response = [this, callback_id](const std::shared_ptr& response) { + ScopeLogger("Entered into asynchronous function, get_response"); JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -494,11 +531,12 @@ void ContactInstance::ContactManagerFind(const JsonValue& args, JsonObject& out) } void ContactInstance::ContactManagerFindByUsageCount(const JsonValue& args, JsonObject& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); const double callback_id = args.get("callbackId").get(); auto get = [this, args](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); JsonValue result = JsonValue(JsonArray()); PlatformResult status = ContactManager::ContactManagerFindByUsageCount( @@ -511,6 +549,7 @@ void ContactInstance::ContactManagerFindByUsageCount(const JsonValue& args, Json }; auto get_response = [this, callback_id](const std::shared_ptr& response) { + ScopeLogger("Entered into asynchronous function, get_response"); JsonObject& obj = response->get(); obj["callbackId"] = picojson::value(static_cast(callback_id)); Instance::PostMessage(this, response->serialize().c_str()); @@ -522,6 +561,7 @@ void ContactInstance::ContactManagerFindByUsageCount(const JsonValue& args, Json } void ContactInstance::ContactManagerImportFromVCard(const JsonValue& args, JsonObject& out) { + ScopeLogger(); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerImportFromVCard( common::JsonCast(args), val.get()); @@ -532,6 +572,7 @@ void ContactInstance::ContactManagerImportFromVCard(const JsonValue& args, JsonO } void ContactInstance::ContactManagerStartListening(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerStartListening( @@ -543,6 +584,7 @@ void ContactInstance::ContactManagerStartListening(const JsonValue& args, JsonOb } void ContactInstance::ContactManagerStopListening(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactRead, &out); JsonValue val{JsonObject{}}; PlatformResult status = ContactManager::ContactManagerStopListening( @@ -554,6 +596,7 @@ void ContactInstance::ContactManagerStopListening(const JsonValue& args, JsonObj } void ContactInstance::PersonLink(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = @@ -565,6 +608,7 @@ void ContactInstance::PersonLink(const JsonValue& args, JsonObject& out) { } void ContactInstance::PersonUnlink(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); JsonValue val{JsonObject{}}; PlatformResult status = @@ -588,6 +632,7 @@ void ContactInstance::PersonGetUsageCount(const JsonValue& args, JsonObject& out } void ContactInstance::PersonResetUsageCount(const JsonValue& args, JsonObject& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContactWrite, &out); PlatformResult status = Person::PersonResetUsageCount(common::JsonCast(args)); if (status.IsSuccess()) { diff --git a/src/contact/contact_manager.cc b/src/contact/contact_manager.cc index e6c519a..6fe6b98 100644 --- a/src/contact/contact_manager.cc +++ b/src/contact/contact_manager.cc @@ -42,7 +42,7 @@ const char* kTokenDelimiter = " ,:"; using namespace common; PlatformResult ContactManagerGetAddressBooks(const JsonObject& args, JsonArray& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -113,7 +113,7 @@ PlatformResult ContactManagerGetAddressBooks(const JsonObject& args, JsonArray& } PlatformResult ContactManagerGetAddressBook(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -152,7 +152,7 @@ PlatformResult ContactManagerGetAddressBook(const JsonObject& args, JsonObject& namespace { PlatformResult ContactManagerGetInternal(int person_id, JsonObject* out) { - LoggerD("Enter"); + ScopeLogger(); contacts_record_h contacts_record = nullptr; int error_code = contacts_db_get_record(_contacts_person._uri, person_id, &contacts_record); @@ -179,7 +179,7 @@ PlatformResult ContactManagerGetInternal(int person_id, JsonObject* out) { } PlatformResult ContactManagerAddAddressBook(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -227,7 +227,7 @@ PlatformResult ContactManagerAddAddressBook(const JsonObject& args, JsonObject& } PlatformResult ContactManagerRemoveAddressBook(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -252,7 +252,7 @@ PlatformResult ContactManagerRemoveAddressBook(const JsonObject& args, JsonObjec } PlatformResult ContactManagerGet(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -262,7 +262,7 @@ PlatformResult ContactManagerGet(const JsonObject& args, JsonObject& out) { } PlatformResult ContactManagerUpdate(const JsonObject& args, JsonObject&) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -292,7 +292,7 @@ PlatformResult ContactManagerUpdate(const JsonObject& args, JsonObject&) { } PlatformResult ContactManagerUpdateBatch(const JsonObject& args) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -340,7 +340,7 @@ PlatformResult ContactManagerUpdateBatch(const JsonObject& args) { } PlatformResult ContactManagerRemove(const JsonObject& args, JsonObject&) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -360,7 +360,7 @@ PlatformResult ContactManagerRemove(const JsonObject& args, JsonObject&) { } PlatformResult ContactManagerRemoveBatch(const JsonObject& args) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -387,7 +387,7 @@ PlatformResult ContactManagerRemoveBatch(const JsonObject& args) { } PlatformResult ContactManagerFind(const JsonObject& args, JsonArray& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -778,7 +778,7 @@ PlatformResult ContactManagerFind(const JsonObject& args, JsonArray& out) { } PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; contacts_query_h contacts_query = nullptr; @@ -961,7 +961,7 @@ PlatformResult ContactManagerFindByUsageCount(const JsonObject& args, JsonArray& } PlatformResult ContactManagerImportFromVCard(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); // I'm not sure how to call it. Should it be 'Contact', 'vCard' or what? PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -1011,7 +1011,7 @@ bool IsNumeric(const char* s) { } void ContactManagerListenerCallback(const char* view_uri, char* changes, void* user_data) { - LoggerD("ContactManagerListenerCallback"); + ScopeLogger("ContactManagerListenerCallback"); (void)view_uri; @@ -1111,7 +1111,7 @@ void ContactManagerListenerCallback(const char* view_uri, char* changes, void* u PlatformResult ContactManagerStartListening(ContactInstance& instance, const JsonObject& /*args*/, JsonObject& /*out*/) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -1129,7 +1129,7 @@ PlatformResult ContactManagerStartListening(ContactInstance& instance, const Jso PlatformResult ContactManagerStopListening(ContactInstance& instance, const JsonObject& /*args*/, JsonObject& /*out*/) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; diff --git a/src/contact/contact_search_engine.cc b/src/contact/contact_search_engine.cc index 5bc09e6..2769e2c 100644 --- a/src/contact/contact_search_engine.cc +++ b/src/contact/contact_search_engine.cc @@ -217,17 +217,17 @@ ContactSearchEngine::ContactSearchEngine() is_filter_set_(false), is_sort_mode_set_(false), is_sort_mode_asc_(false) { - LoggerD("Entered"); + ScopeLogger(); } void ContactSearchEngine::SetAddressBookId(long id) { - LoggerD("Entered"); + ScopeLogger(); addressbook_id_ = id; is_addressbook_id_is_set_ = true; } common::PlatformResult ContactSearchEngine::ApplyFilter(const picojson::value& filter, int depth) { - LoggerD("Entered"); + ScopeLogger(); if (!filter.is()) { return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Failed to set filter"); @@ -287,7 +287,7 @@ common::PlatformResult ContactSearchEngine::ApplyFilter(const picojson::value& f } PlatformResult ContactSearchEngine::SetSortMode(const picojson::value& sort_mode) { - LoggerD("Entered"); + ScopeLogger(); if (!sort_mode.is()) { return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Failed to set sort mode"); @@ -309,7 +309,7 @@ PlatformResult ContactSearchEngine::SetSortMode(const picojson::value& sort_mode } common::PlatformResult ContactSearchEngine::Find(picojson::array* out) { - LoggerD("Entered"); + ScopeLogger(); if (is_filter_set_) { if (is_sort_mode_set_) { @@ -347,7 +347,7 @@ PlatformResult ContactSearchEngine::ApplyAttributeFilter(const std::string& name common::AttributeMatchFlag match_flag, const picojson::value& match_value, int depth) { - LoggerD("Entered"); + ScopeLogger(); LongSetPtr id_set = LongSetPtr(new LongSet()); @@ -465,7 +465,7 @@ PlatformResult ContactSearchEngine::ApplyAttributeRangeFilter(const std::string& const picojson::value& initial_value, const picojson::value& end_value, int depth) { - LoggerD("Entered"); + ScopeLogger(); bool initial_value_set = (!IsNull(initial_value)); bool end_value_set = (!IsNull(end_value)); @@ -570,7 +570,7 @@ PlatformResult ContactSearchEngine::ApplyAttributeRangeFilter(const std::string& PlatformResult ContactSearchEngine::GetAllContactsSorted( const FilterPropertyStruct& attribute_properties, bool is_ascending, picojson::array* out) { - LoggerD("Entered"); + ScopeLogger(); LongVectorPtr sorted_ids = LongVectorPtr(new LongVector()); SortContacts(attribute_properties, sorted_ids, is_ascending); @@ -579,7 +579,7 @@ PlatformResult ContactSearchEngine::GetAllContactsSorted( } PlatformResult ContactSearchEngine::GetAllContacts(picojson::array* out) { - LoggerD("Entered"); + ScopeLogger(); contacts_list_h list = nullptr; int error_code = 0; @@ -663,7 +663,7 @@ PlatformResult ContactSearchEngine::GetAllContacts(picojson::array* out) { template PlatformResult ContactSearchEngine::GetContacts(Iterator begin, Iterator end, picojson::array* out) { - LoggerD("Entered"); + ScopeLogger(); for (auto iter = begin; iter != end; ++iter) { const auto id = *iter; @@ -715,7 +715,7 @@ common::PlatformResult ContactSearchEngine::GetQueryResults(contacts_query_h que contacts_filter_h filter, unsigned int property_id, LongSetPtr result) { - LoggerD("Entered"); + ScopeLogger(); int error_code = contacts_query_set_filter(query, filter); auto status = ContactUtil::ErrorChecker(error_code, "Failed contacts_query_set_filter"); @@ -757,7 +757,7 @@ common::PlatformResult ContactSearchEngine::GetQueryResults(contacts_query_h que PlatformResult ContactSearchEngine::QueryAttributeBool( const FilterPropertyStruct& attribute_properties, LongSetPtr result, bool match_value) { - LoggerD("Entered"); + ScopeLogger(); const char* view_uri = attribute_properties.view_uri; unsigned int property_contact_id = attribute_properties.property_contact_id; @@ -788,7 +788,7 @@ PlatformResult ContactSearchEngine::QueryAttributeBool( PlatformResult ContactSearchEngine::QueryAttributeInt( const FilterPropertyStruct& attribute_properties, LongSetPtr result, contacts_match_int_flag_e match, int match_value) { - LoggerD("Entered"); + ScopeLogger(); const char* view_uri = attribute_properties.view_uri; unsigned int property_contact_id = attribute_properties.property_contact_id; @@ -819,7 +819,7 @@ PlatformResult ContactSearchEngine::QueryAttributeInt( PlatformResult ContactSearchEngine::QueryAttributeString( const FilterPropertyStruct& attribute_properties, LongSetPtr result, contacts_match_str_flag_e match, const char* match_value) { - LoggerD("Entered"); + ScopeLogger(); const char* view_uri = attribute_properties.view_uri; unsigned int property_contact_id = attribute_properties.property_contact_id; @@ -854,7 +854,7 @@ PlatformResult ContactSearchEngine::QueryAttributeString( PlatformResult ContactSearchEngine::QueryAttributeDate( const std::string& attr_name, const FilterPropertyStruct& attribute_properties, LongSetPtr result, contacts_match_int_flag_e match, int match_value) { - LoggerD("Entered"); + ScopeLogger(); const char* view_uri = attribute_properties.view_uri; unsigned int property_contact_id = attribute_properties.property_contact_id; @@ -905,7 +905,7 @@ PlatformResult ContactSearchEngine::QueryAttributeDate( PlatformResult ContactSearchEngine::QueryAttributeRangeBool( const FilterPropertyStruct& attribute_properties, LongSetPtr result, bool initial_value_is_set, bool initial_value, bool end_value_is_set, bool end_value) { - LoggerD("Entered"); + ScopeLogger(); const char* view_uri = attribute_properties.view_uri; unsigned int property_contact_id = attribute_properties.property_contact_id; @@ -958,7 +958,7 @@ PlatformResult ContactSearchEngine::QueryAttributeRangeBool( PlatformResult ContactSearchEngine::QueryAttributeRangeInt( const FilterPropertyStruct& attribute_properties, LongSetPtr result, bool initial_value_is_set, int initial_value, bool end_value_is_set, int end_value) { - LoggerD("Entered"); + ScopeLogger(); const char* view_uri = attribute_properties.view_uri; unsigned int property_contact_id = attribute_properties.property_contact_id; @@ -1023,7 +1023,7 @@ PlatformResult ContactSearchEngine::QueryAttributeRangeInt( PlatformResult ContactSearchEngine::QueryAttributeRangeString( const FilterPropertyStruct& attribute_properties, LongSetPtr result, const char* initial_value, const char* end_value) { - LoggerD("Entered"); + ScopeLogger(); const char* view_uri = attribute_properties.view_uri; unsigned int property_contact_id = attribute_properties.property_contact_id; @@ -1088,7 +1088,7 @@ PlatformResult ContactSearchEngine::QueryAttributeRangeDate( const std::string& attr_name, const FilterPropertyStruct& attribute_properties, LongSetPtr result, bool initial_value_is_set, int initial_value, bool end_value_is_set, int end_value) { - LoggerD("Entered"); + ScopeLogger(); const char* view_uri = attribute_properties.view_uri; unsigned int property_contact_id = attribute_properties.property_contact_id; @@ -1161,7 +1161,7 @@ PlatformResult ContactSearchEngine::QueryAttributeRangeDate( PlatformResult ContactSearchEngine::SortContacts(const FilterPropertyStruct& attribute_properties, LongVectorPtr result, bool is_ascending, LongSetPtr ids) { - LoggerD("Entered"); + ScopeLogger(); const char* view_uri = attribute_properties.view_uri; unsigned int property_contact_id = attribute_properties.property_contact_id; @@ -1253,7 +1253,7 @@ PlatformResult ContactSearchEngine::SortContacts(const FilterPropertyStruct& att PlatformResult ContactSearchEngine::SortContacts(const FilterPropertyStruct& attribute_properties, LongVectorPtr result, bool is_ascending) { - LoggerD("Entered"); + ScopeLogger(); const char* view_uri = attribute_properties.view_uri; unsigned int property_contact_id = attribute_properties.property_contact_id; diff --git a/src/contact/contact_util.cc b/src/contact/contact_util.cc index 6dd2c1c..52b6aa0 100644 --- a/src/contact/contact_util.cc +++ b/src/contact/contact_util.cc @@ -151,7 +151,7 @@ static const char kContactInstantMessageTypeCustom[] = "CUSTOM"; } PlatformResult ErrorChecker(int err, const char* message) { - LoggerD("Enter"); + ScopeLogger(); if (CONTACTS_ERROR_NONE != err) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, message); } @@ -160,7 +160,7 @@ PlatformResult ErrorChecker(int err, const char* message) { } PlatformResult GetStrFromRecord(contacts_record_h record, unsigned int property_id, char** value) { - LoggerD("Enter"); + ScopeLogger(); int err = contacts_record_get_str_p(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error during getting contact record", @@ -171,7 +171,7 @@ PlatformResult GetStrFromRecord(contacts_record_h record, unsigned int property_ } PlatformResult GetIntFromRecord(contacts_record_h record, unsigned int property_id, int* value) { - LoggerD("Enter"); + ScopeLogger(); int err = contacts_record_get_int(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error during getting contact record", @@ -182,7 +182,7 @@ PlatformResult GetIntFromRecord(contacts_record_h record, unsigned int property_ } PlatformResult GetBoolFromRecord(contacts_record_h record, unsigned int property_id, bool* value) { - LoggerD("Enter"); + ScopeLogger(); int err = contacts_record_get_bool(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error during getting contact record", @@ -194,7 +194,7 @@ PlatformResult GetBoolFromRecord(contacts_record_h record, unsigned int property PlatformResult SetStrInRecord(contacts_record_h record, unsigned int property_id, const char* value) { - LoggerD("Enter"); + ScopeLogger(); int err = contacts_record_set_str(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { return LogAndCreateResult( @@ -206,7 +206,7 @@ PlatformResult SetStrInRecord(contacts_record_h record, unsigned int property_id } PlatformResult SetIntInRecord(contacts_record_h record, unsigned int property_id, int value) { - LoggerD("Enter"); + ScopeLogger(); int err = contacts_record_set_int(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error during setting contact record", @@ -217,7 +217,7 @@ PlatformResult SetIntInRecord(contacts_record_h record, unsigned int property_id } PlatformResult SetBoolInRecord(contacts_record_h record, unsigned int property_id, bool value) { - LoggerD("Enter"); + ScopeLogger(); int err = contacts_record_set_bool(record, property_id, value); if (CONTACTS_ERROR_NONE != err) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error during setting contact record", @@ -228,7 +228,7 @@ PlatformResult SetBoolInRecord(contacts_record_h record, unsigned int property_i } PlatformResult ClearAllContactRecord(contacts_record_h contacts_record, unsigned int property_id) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -266,7 +266,7 @@ PlatformResult ClearAllContactRecord(contacts_record_h contacts_record, unsigned PlatformResult GetNumberOfChildRecord(contacts_record_h contacts_record, unsigned int property_id, int* child_count) { - LoggerD("Enter"); + ScopeLogger(); Assert(child_count); int err = contacts_record_get_child_record_count(contacts_record, property_id, child_count); @@ -279,7 +279,7 @@ PlatformResult GetNumberOfChildRecord(contacts_record_h contacts_record, unsigne PlatformResult ImportContactNameFromContactsRecord(contacts_record_h contacts_record, JsonObject* out_ptr, bool* is_contact_name) { - LoggerD("Enter"); + ScopeLogger(); JsonObject& out = *out_ptr; if (!contacts_record) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Contacts record is null"); @@ -418,7 +418,7 @@ PlatformResult ImportContactNameFromContactsRecord(contacts_record_h contacts_re PlatformResult ExportContactNameToContactsRecord(contacts_record_h contacts_record, const JsonObject& in) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -563,7 +563,7 @@ PlatformResult ExportContactNameToContactsRecord(contacts_record_h contacts_reco PlatformResult ImportContactEmailAddressFromContactsRecord(contacts_record_h contacts_record, unsigned int index, JsonObject* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -641,7 +641,7 @@ PlatformResult ImportContactEmailAddressFromContactsRecord(contacts_record_h con PlatformResult ExportContactEmailAddressToContactsRecord(contacts_record_h contacts_record, const JsonObject& in) { - LoggerD("Enter"); + ScopeLogger(); contacts_record_h c_email_record_h = nullptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -719,7 +719,7 @@ PlatformResult ExportContactEmailAddressToContactsRecord(contacts_record_h conta PlatformResult ImportContactPhoneNumberFromContactsRecord(contacts_record_h contacts_record, unsigned int index, JsonObject* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); JsonObject& out = *out_ptr; contacts_record_h child_record = nullptr; // contacts_record is protected by unique_ptr and its ownership is not passed @@ -827,7 +827,7 @@ PlatformResult ImportContactPhoneNumberFromContactsRecord(contacts_record_h cont PlatformResult ExportContactPhoneNumberToContactsRecord(contacts_record_h contacts_record, const JsonObject& in) { - LoggerD("Enter"); + ScopeLogger(); contacts_record_h phone_record = nullptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -930,7 +930,7 @@ PlatformResult ExportContactPhoneNumberToContactsRecord(contacts_record_h contac PlatformResult ImportContactOrganizationFromContactsRecord(contacts_record_h contacts_record, unsigned int index, JsonObject* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -993,7 +993,7 @@ PlatformResult ImportContactOrganizationFromContactsRecord(contacts_record_h con PlatformResult ExportContactOrganizationToContactsRecord(contacts_record_h contacts_record, const JsonObject& in) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -1068,7 +1068,7 @@ PlatformResult ExportContactOrganizationToContactsRecord(contacts_record_h conta PlatformResult ImportContactWebSiteFromContactsRecord(contacts_record_h contacts_record, unsigned int index, JsonObject* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1109,7 +1109,7 @@ PlatformResult ImportContactWebSiteFromContactsRecord(contacts_record_h contacts PlatformResult ExportContactWebSiteToContactsRecord(contacts_record_h contacts_record, const JsonObject& in) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -1170,7 +1170,7 @@ PlatformResult ExportContactWebSiteToContactsRecord(contacts_record_h contacts_r PlatformResult ImportContactAnniversariesFromContactsRecord(contacts_record_h contacts_record, unsigned int index, JsonObject* out_ptr, bool* ret) { - LoggerD("Enter"); + ScopeLogger(); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1223,7 +1223,7 @@ PlatformResult ImportContactAnniversariesFromContactsRecord(contacts_record_h co PlatformResult ExportContactAnniversariesToContactsRecord(contacts_record_h contacts_record, const JsonObject& in) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -1285,7 +1285,7 @@ PlatformResult ExportContactAnniversariesToContactsRecord(contacts_record_h cont PlatformResult ImportContactRelationshipFromContactsRecord(contacts_record_h contacts_record, unsigned int index, JsonObject* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1408,7 +1408,7 @@ PlatformResult ImportContactRelationshipFromContactsRecord(contacts_record_h con PlatformResult ExportContactRelationshipToContactsRecord(contacts_record_h contacts_record, const JsonObject& in) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -1498,7 +1498,7 @@ PlatformResult ExportContactRelationshipToContactsRecord(contacts_record_h conta PlatformResult ImportContactExtensionFromContactsRecord(contacts_record_h contacts_record, unsigned int index, JsonObject* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -1524,6 +1524,7 @@ PlatformResult ImportContactExtensionFromContactsRecord(contacts_record_h contac picojson::value(data1 ? JsonValue{static_cast(data1)} : JsonValue{}))); auto insert_data = [&](unsigned int id, const std::string& label) { + ScopeLogger("Entered into asynchronous function, insert_data"); char* data = nullptr; status = ContactUtil::GetStrFromRecord(child_record, id, &data); if (status && data) { @@ -1602,7 +1603,7 @@ PlatformResult ImportContactExtensionFromContactsRecord(contacts_record_h contac PlatformResult ExportContactExtensionToContactsRecord(contacts_record_h contacts_record, const JsonObject& in) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1628,6 +1629,8 @@ PlatformResult ExportContactExtensionToContactsRecord(contacts_record_h contacts } auto set_data = [&](int id, const char* label) { + ScopeLogger("Entered into asynchronous function, set_data"); + if (!IsNull(in, label)) { status = ContactUtil::SetStrInRecord(child_record, id, FromJson(in, label).c_str()); @@ -1716,7 +1719,7 @@ PlatformResult ExportContactExtensionToContactsRecord(contacts_record_h contacts PlatformResult ImportContactInstantMessengerFromContactsRecord(contacts_record_h contacts_record, unsigned int index, JsonObject* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1809,7 +1812,7 @@ PlatformResult ImportContactInstantMessengerFromContactsRecord(contacts_record_h PlatformResult ExportContactInstantMessengerToContactsRecord(contacts_record_h contacts_record, const JsonObject& in) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -1891,7 +1894,7 @@ PlatformResult ExportContactInstantMessengerToContactsRecord(contacts_record_h c PlatformResult ImportContactAddressFromContactsRecord(contacts_record_h contacts_record, unsigned int index, JsonObject* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -1998,7 +2001,7 @@ PlatformResult ImportContactAddressFromContactsRecord(contacts_record_h contacts PlatformResult ExportContactAddressToContactsRecord(contacts_record_h contacts_record, const JsonObject& in) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -2117,7 +2120,7 @@ PlatformResult ExportContactAddressToContactsRecord(contacts_record_h contacts_r PlatformResult ImportContactNotesFromContactsRecord(contacts_record_h contacts_record, unsigned int index, JsonValue* val) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -2147,7 +2150,7 @@ PlatformResult ImportContactNotesFromContactsRecord(contacts_record_h contacts_r PlatformResult ExportNotesToContactsRecord(contacts_record_h contacts_record, const std::string& value) { - LoggerD("Enter"); + ScopeLogger(); contacts_record_h notes_record = nullptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -2185,7 +2188,7 @@ PlatformResult ExportNotesToContactsRecord(contacts_record_h contacts_record, PlatformResult ImportGroupIdsFromContactsRecord(contacts_record_h contacts_record, unsigned int index, JsonValue* val) { - LoggerD("Enter"); + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -2219,7 +2222,7 @@ PlatformResult ImportGroupIdsFromContactsRecord(contacts_record_h contacts_recor } PlatformResult ExportGroupIdsToContactsRecord(contacts_record_h contacts_record, int value) { - LoggerD("Enter"); + ScopeLogger(); contacts_record_h notes_record = nullptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -2259,7 +2262,7 @@ PlatformResult ExportGroupIdsToContactsRecord(contacts_record_h contacts_record, PlatformResult ImportContactFromContactsRecord(contacts_record_h contacts_record, JsonObject* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); JsonObject& out = *out_ptr; // contacts_record is protected by unique_ptr and its ownership is not passed // here @@ -2490,6 +2493,7 @@ PlatformResult ImportContactFromContactsRecord(contacts_record_h contacts_record PlatformResult ExportContactToContactsRecord(contacts_record_h contacts_record, const JsonObject& in) { + ScopeLogger(); // contacts_record is protected by unique_ptr and its ownership is not passed // here if (!contacts_record) { @@ -2898,6 +2902,7 @@ PlatformResult ImportPersonFromContactsRecord(contacts_record_h record, JsonObje * @param[out] contacts_record_h Record which is updated */ PlatformResult ExportPersonToContactsRecord(contacts_record_h record, const JsonObject& args) { + ScopeLogger(); if (nullptr == record) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform person object did not set"); } @@ -2951,6 +2956,7 @@ PlatformResult ExportPersonToContactsRecord(contacts_record_h record, const Json PlatformResult UpdateAdditionalInformation(const contacts_record_h contacts_record, JsonObject* out_ptr) { + ScopeLogger(); JsonObject& out = *out_ptr; int int_value = -1; PlatformResult status = @@ -2991,6 +2997,7 @@ PlatformResult UpdateAdditionalInformation(const contacts_record_h contacts_reco } PlatformResult CheckDBConnection() { + ScopeLogger(); static bool _connected = false; if (_connected) return PlatformResult(ErrorCode::NO_ERROR); diff --git a/src/contact/person.cc b/src/contact/person.cc index f407a34..909d221 100644 --- a/src/contact/person.cc +++ b/src/contact/person.cc @@ -67,7 +67,7 @@ const char* kGetUsageCountResultUsageCount = "usageCount"; }; PlatformResult PersonLink(const JsonObject& args, JsonObject&) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -94,7 +94,7 @@ PlatformResult PersonLink(const JsonObject& args, JsonObject&) { } PlatformResult PersonUnlink(const JsonObject& args, JsonObject& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -151,7 +151,7 @@ PlatformResult PersonUnlink(const JsonObject& args, JsonObject& out) { } PlatformResult GetUsageCount(const JsonObject& args, JsonObject& out) { - LoggerD("Entered"); + ScopeLogger(); // Retrieve person_id long person_id = common::stol(FromJson(args, kGetUsageCountArgPersonId)); @@ -274,7 +274,7 @@ PlatformResult ResetUsageCount(const long& person_id, const std::string& type) { } PlatformResult PersonResetUsageCount(const JsonObject& args) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = ContactUtil::CheckDBConnection(); if (status.IsError()) return status; @@ -291,7 +291,7 @@ PlatformResult PersonResetUsageCount(const JsonObject& args) { } PlatformResult PersonPropertyFromString(const std::string& name, PersonProperty* person_prop) { - LoggerD("Enter"); + ScopeLogger(); auto iter = personPropertyMap.find(name); if (iter == personPropertyMap.end()) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid property name", diff --git a/src/content/content_filter.cc b/src/content/content_filter.cc index 130b0d5..cb69310 100644 --- a/src/content/content_filter.cc +++ b/src/content/content_filter.cc @@ -57,7 +57,7 @@ std::map const attributeNameMap = { }; std::string escapeValueString(const std::string& data) { - LoggerD("Enter"); + ScopeLogger(); std::string out; // If string won't be resized, then it will be faster out.reserve(data.size()); @@ -81,7 +81,7 @@ std::string escapeValueString(const std::string& data) { } // namespace PlatformResult ContentFilter::MapField(const std::string& name, std::string* result) { - LoggerD("Enter"); + ScopeLogger(); auto it = attributeNameMap.find(name); if (it != attributeNameMap.end()) { *result = it->second; @@ -93,13 +93,13 @@ PlatformResult ContentFilter::MapField(const std::string& name, std::string* res PlatformResult ContentFilter::BuildQuery(const picojson::object& jsFilter, std::string* queryToCall) { - LoggerD("Enter"); + ScopeLogger(); std::vector> partialqueries; partialqueries.push_back(std::vector()); visitor.SetOnAttributeFilter([&](const std::string& name, AttributeMatchFlag match_flag, const picojson::value& match_value) { - LoggerD("entered OnAttributeFilter"); + ScopeLogger("Entered into asynchronous function, visitor.SetOnAttributeFilter's argument"); std::string query; std::string matchValue; @@ -162,13 +162,13 @@ PlatformResult ContentFilter::BuildQuery(const picojson::object& jsFilter, }); visitor.SetOnCompositeFilterBegin([&](CompositeFilterType type) { - LoggerD("entered OnCompositeFilterBegin"); + ScopeLogger("Entered into asynchronous function, visitor.SetOnCompositeFilterBegin's argument"); partialqueries.push_back(std::vector()); return PlatformResult(ErrorCode::NO_ERROR); }); visitor.SetOnCompositeFilterEnd([&](CompositeFilterType calType) { - LoggerD("entered OnCompositeFilterEnd"); + ScopeLogger("Entered into asynchronous function, visitor.SetOnCompositeFilterEnd's argument"); std::string finalQuery; std::string separator; @@ -200,7 +200,7 @@ PlatformResult ContentFilter::BuildQuery(const picojson::object& jsFilter, visitor.SetOnAttributeRangeFilter([&](const std::string& name, const picojson::value& initial_value, const picojson::value& end_value) { - LoggerD("entered OnAttributeFilter"); + ScopeLogger("Entered into asynchronous function, visitor.SetOnAttributeRangeFilter's argument"); std::string query = ""; std::string paramName; diff --git a/src/content/content_instance.cc b/src/content/content_instance.cc index 587bca6..6722aa5 100644 --- a/src/content/content_instance.cc +++ b/src/content/content_instance.cc @@ -52,6 +52,7 @@ ContentInstance::ContentInstance() listener_handle_(nullptr), listener_data_(nullptr), callback_data_(nullptr) { + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -92,7 +93,7 @@ ContentInstance::ContentInstance() } ContentInstance::~ContentInstance() { - LoggerD("entered"); + ScopeLogger(); if (noti_handle_) { media_content_remove_db_updated_cb(noti_handle_); @@ -118,7 +119,7 @@ ContentInstance::~ContentInstance() { } static gboolean CompletedCallback(const std::shared_ptr& user_data) { - LoggerD("entered"); + ScopeLogger(); picojson::object out; out["callbackId"] = picojson::value(user_data->callbackId); @@ -135,7 +136,7 @@ static gboolean CompletedCallback(const std::shared_ptr& user } static void* WorkThread(const std::shared_ptr& user_data) { - LoggerD("entered"); + ScopeLogger(); int ret = MEDIA_CONTENT_ERROR_NONE; ContentCallbacks cbType = user_data->cbType; @@ -224,7 +225,7 @@ static void* WorkThread(const std::shared_ptr& user_data) { } static void ScanDirectoryCallback(media_content_error_e error, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); ReplyCallbackData* cbData = (ReplyCallbackData*)user_data; @@ -247,7 +248,7 @@ static void changedContentV1Callback(media_content_error_e error, int pid, media_content_db_update_type_e update_type, media_content_type_e media_type, char* uuid, char* path, char* mime_type, void* user_data) { - LoggerD("Entered file change callback"); + ScopeLogger("File change callback"); if (error != MEDIA_CONTENT_ERROR_NONE) { LOGGER(ERROR) << "Media content changed callback error: " << error; @@ -302,7 +303,7 @@ static void changedContentV2Callback(media_content_error_e error, int pid, media_content_db_update_type_e update_type, media_content_type_e media_type, char* uuid, char* path, char* mime_type, void* user_data) { - LoggerD("Entered directory change callback"); + ScopeLogger("Directory change callback"); if (error != MEDIA_CONTENT_ERROR_NONE) { LOGGER(ERROR) << "Media content changed v2 callback error: " << error; @@ -353,7 +354,7 @@ static void changedContentV2Callback(media_content_error_e error, int pid, static PlatformResult prepareDirectoryChangeResponse(media_content_db_update_type_e update_type, char* uuid, picojson::object& obj) { - LoggerD("Media item is a directory"); + ScopeLogger("Media item is a directory"); if (MEDIA_CONTENT_DELETE == update_type) { ReportSuccess(picojson::value(std::string(uuid)), obj); @@ -392,7 +393,7 @@ static PlatformResult prepareDirectoryChangeResponse(media_content_db_update_typ static PlatformResult prepareFileChangeResponse(media_content_db_update_type_e update_type, char* uuid, picojson::object& obj) { - LoggerD("Media item is a file"); + ScopeLogger("Media item is a file"); if (MEDIA_CONTENT_DELETE == update_type) { ReportSuccess(picojson::value(std::string(uuid)), obj); @@ -434,7 +435,7 @@ static void contentChangeCallback(media_content_error_e error, int pid, media_content_db_update_type_e update_type, media_content_type_e media_type, char* uuid, char* path, char* mime_type, void* user_data) { - LoggerD("Entered directory and file change callback"); + ScopeLogger("directory and file change callback"); if (MEDIA_CONTENT_ERROR_NONE != error) { LoggerE("Failed to perform contentChangeCallback: %d", error); @@ -485,7 +486,7 @@ static void contentChangeCallback(media_content_error_e error, int pid, } void ContentInstance::ContentManagerUpdate(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); if (ContentManager::getInstance()->isConnected()) { @@ -501,8 +502,7 @@ void ContentInstance::ContentManagerUpdate(const picojson::value& args, picojson void ContentInstance::ContentManagerUpdatebatch(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); - LoggerE("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); double callbackId = args.get("callbackId").get(); @@ -520,7 +520,7 @@ void ContentInstance::ContentManagerUpdatebatch(const picojson::value& args, } void ContentInstance::ContentManagerGetdirectories(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_EXIST(args, "callbackId", out) double callbackId = args.get("callbackId").get(); @@ -538,7 +538,7 @@ void ContentInstance::ContentManagerGetdirectories(const picojson::value& args, common::TaskQueue::GetInstance().Queue(WorkThread, CompletedCallback, cbData); } void ContentInstance::ContentManagerFind(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); // CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -560,7 +560,7 @@ void ContentInstance::ContentManagerFind(const picojson::value& args, picojson:: } void ContentInstance::ContentManagerScanfile(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); CHECK_EXIST(args, "callbackId", out) @@ -581,7 +581,7 @@ void ContentInstance::ContentManagerScanfile(const picojson::value& args, picojs void ContentInstance::ContentManagerScanDirectory(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); CHECK_EXIST(args, "callbackId", out) @@ -602,7 +602,7 @@ void ContentInstance::ContentManagerScanDirectory(const picojson::value& args, void ContentInstance::ContentManagerCancelScanDirectory(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); CHECK_EXIST(args, "contentDirURI", out) @@ -617,7 +617,7 @@ void ContentInstance::ContentManagerCancelScanDirectory(const picojson::value& a void ContentInstance::ContentManagerAddChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); callback_data_ = new ReplyCallbackData(); callback_data_->instance = this; @@ -641,7 +641,7 @@ void ContentInstance::ContentManagerAddChangeListener(const picojson::value& arg void ContentInstance::ContentManagerRemoveChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult result = ContentManager::getInstance()->removeChangeListener(listener_handle_); @@ -656,7 +656,7 @@ void ContentInstance::ContentManagerRemoveChangeListener(const picojson::value& void ContentInstance::ContentManagerSetchangelistener(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); LoggerW( "DEPRECATION WARNING: setChangeListener() is deprecated and will be removed from next " "release. " @@ -700,7 +700,7 @@ void ContentInstance::ContentManagerSetchangelistener(const picojson::value& arg void ContentInstance::ContentManagerUnsetchangelistener(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); LoggerW( "DEPRECATION WARNING: unsetChangeListener() is deprecated and will be removed from next " "release. " @@ -720,7 +720,7 @@ void ContentInstance::ContentManagerUnsetchangelistener(const picojson::value& a void ContentInstance::ContentManagerGetplaylists(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); // CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -744,7 +744,7 @@ void ContentInstance::ContentManagerGetplaylists(const picojson::value& args, } void ContentInstance::ContentManagerCreateplaylist(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); CHECK_EXIST(args, "callbackId", out) @@ -767,7 +767,7 @@ void ContentInstance::ContentManagerCreateplaylist(const picojson::value& args, } void ContentInstance::ContentManagerRemoveplaylist(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); double callbackId = args.get("callbackId").get(); @@ -789,7 +789,7 @@ void ContentInstance::ContentManagerRemoveplaylist(const picojson::value& args, void ContentInstance::ContentManagerCreateThumbnail(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); common::PlatformResult result = common::PlatformResult(common::ErrorCode::NO_ERROR); @@ -806,7 +806,7 @@ void ContentInstance::ContentManagerCreateThumbnail(const picojson::value& args, void ContentInstance::ContentManagerPlaylistAdd(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); if (ContentManager::getInstance()->isConnected()) { @@ -824,7 +824,7 @@ void ContentInstance::ContentManagerPlaylistAdd(const picojson::value& args, void ContentInstance::ContentManagerPlaylistAddbatch(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); double callbackId = args.get("callbackId").get(); @@ -844,7 +844,7 @@ void ContentInstance::ContentManagerPlaylistAddbatch(const picojson::value& args void ContentInstance::ContentManagerPlaylistGet(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); // CHECK_PRIVILEGE_ACCESS(kPrivilegeContentRead, &out); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); @@ -865,7 +865,7 @@ void ContentInstance::ContentManagerPlaylistGet(const picojson::value& args, void ContentInstance::ContentManagerPlaylistRemove(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); if (ContentManager::getInstance()->isConnected()) { @@ -883,7 +883,7 @@ void ContentInstance::ContentManagerPlaylistRemove(const picojson::value& args, void ContentInstance::ContentManagerPlaylistRemovebatch(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); double callbackId = args.get("callbackId").get(); @@ -903,7 +903,7 @@ void ContentInstance::ContentManagerPlaylistRemovebatch(const picojson::value& a void ContentInstance::ContentManagerPlaylistSetorder(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); double callbackId = args.get("callbackId").get(); @@ -923,7 +923,7 @@ void ContentInstance::ContentManagerPlaylistSetorder(const picojson::value& args void ContentInstance::ContentManagerPlaylistMove(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); double callbackId = args.get("callbackId").get(); @@ -943,8 +943,7 @@ void ContentInstance::ContentManagerPlaylistMove(const picojson::value& args, void ContentInstance::ContentManagerAudioGetLyrics(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); - LOGGER(DEBUG) << "entered"; + ScopeLogger(); picojson::object lyrics; if (ContentManager::getInstance()->isConnected()) { @@ -961,7 +960,7 @@ void ContentInstance::ContentManagerAudioGetLyrics(const picojson::value& args, } void ContentInstance::PlaylistGetName(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); int ret; CHECK_EXIST(args, "id", out) int id = static_cast(args.get("id").get()); @@ -975,7 +974,7 @@ void ContentInstance::PlaylistGetName(const picojson::value& args, picojson::obj } void ContentInstance::PlaylistSetName(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); int ret; @@ -992,7 +991,7 @@ void ContentInstance::PlaylistSetName(const picojson::value& args, picojson::obj } void ContentInstance::PlaylistGetThumbnailUri(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); int ret; CHECK_EXIST(args, "id", out) int id = static_cast(args.get("id").get()); @@ -1006,7 +1005,7 @@ void ContentInstance::PlaylistGetThumbnailUri(const picojson::value& args, picoj } void ContentInstance::PlaylistSetThumbnailUri(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeContentWrite, &out); int ret; @@ -1024,7 +1023,7 @@ void ContentInstance::PlaylistSetThumbnailUri(const picojson::value& args, picoj void ContentInstance::PlaylistGetNumberOfTracks(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_EXIST(args, "id", out) int id = static_cast(args.get("id").get()); int count = 0; diff --git a/src/content/content_manager.cc b/src/content/content_manager.cc index 3895e3e..c12e3db 100644 --- a/src/content/content_manager.cc +++ b/src/content/content_manager.cc @@ -59,7 +59,7 @@ const std::map orientationMap = { }; std::string get_date(char* tmpStr) { - LoggerD("Enter"); + ScopeLogger(); if (tmpStr) { struct tm* result = (struct tm*)calloc(1, sizeof(struct tm)); if (nullptr != result) { @@ -79,7 +79,7 @@ std::string get_date(char* tmpStr) { } void ContentToJson(media_info_h info, picojson::object& o) { - LoggerD("Enter"); + ScopeLogger(); int ret; int tmpInt = 0; bool tmpBool = false; @@ -356,7 +356,7 @@ void ContentToJson(media_info_h info, picojson::object& o) { } void ContentDirToJson(media_folder_h folder, picojson::object& o) { - LoggerD("Enter"); + ScopeLogger(); int ret; char* tmpStr = NULL; media_content_storage_e storage_type; @@ -412,7 +412,7 @@ void ContentDirToJson(media_folder_h folder, picojson::object& o) { } static int setContent(media_info_h media, const picojson::value& content) { - LoggerD("Enter"); + ScopeLogger(); int ret; std::string name = content.get("name").to_str(); @@ -496,7 +496,7 @@ static int setContent(media_info_h media, const picojson::value& content) { } static void FolderToJson(media_folder_h folder, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); char* name = NULL; char* id = NULL; @@ -565,7 +565,7 @@ static void FolderToJson(media_folder_h folder, picojson::object* out) { } static bool media_foreach_directory_cb(media_folder_h folder, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::array* array = static_cast(user_data); picojson::object json; FolderToJson(folder, &json); @@ -574,7 +574,7 @@ static bool media_foreach_directory_cb(media_folder_h folder, void* user_data) { } static bool media_foreach_content_cb(media_info_h media, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::value::array* contents = static_cast(user_data); picojson::value::object o; ContentToJson(media, o); @@ -583,7 +583,7 @@ static bool media_foreach_content_cb(media_info_h media, void* user_data) { } static bool playlist_foreach_cb(media_playlist_h playlist, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::value::array* playlists = static_cast(user_data); picojson::value::object o; if (playlist != NULL) { @@ -634,7 +634,7 @@ static bool playlist_foreach_cb(media_playlist_h playlist, void* user_data) { static bool playlist_content_member_cb(int playlist_member_id, media_info_h media, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::value::array* contents = static_cast(user_data); picojson::value::object o; @@ -645,7 +645,7 @@ static bool playlist_content_member_cb(int playlist_member_id, media_info_h medi } void CreateThumbnailCallback(media_content_error_e err, const char* path, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); unsigned int* callbackId = (unsigned int*)user_data; if (nullptr == callbackId) { @@ -678,7 +678,7 @@ void CreateThumbnailCallback(media_content_error_e err, const char* path, void* } ContentManager::ContentManager() { - LoggerD("ContentManager called"); + ScopeLogger("ContentManager called"); if (media_content_connect() == MEDIA_CONTENT_ERROR_NONE) { m_dbConnected = true; } else { @@ -688,7 +688,7 @@ ContentManager::ContentManager() { } ContentManager::~ContentManager() { - LoggerD("Enter"); + ScopeLogger(); if (m_dbConnected) { if (media_content_disconnect() == MEDIA_CONTENT_ERROR_NONE) { m_dbConnected = false; @@ -697,28 +697,28 @@ ContentManager::~ContentManager() { } ContentManager* ContentManager::getInstance() { - LoggerD("Enter"); + ScopeLogger(); static ContentManager instance; return &instance; } ContentInstance* ContentManager::getContentInstance() { - LoggerD("Enter"); + ScopeLogger(); return m_contentInstance; } void ContentManager::setContentInstance(ContentInstance* const content_instance) { - LoggerD("Enter"); + ScopeLogger(); m_contentInstance = content_instance; } bool ContentManager::isConnected() { - LoggerD("Enter"); + ScopeLogger(); return m_dbConnected; } void ContentManager::getDirectories(const std::shared_ptr& user_data) { - LoggerD("Enter"); + ScopeLogger(); int ret; filter_h filter = NULL; ret = media_filter_create(&filter); @@ -748,7 +748,7 @@ void ContentManager::getDirectories(const std::shared_ptr& us } void ContentManager::find(const std::shared_ptr& user_data) { - LoggerD("Enter"); + ScopeLogger(); int ret; int count, offset; @@ -837,13 +837,13 @@ void ContentManager::find(const std::shared_ptr& user_data) { } int ContentManager::scanFile(std::string& uri) { - LoggerD("Enter"); + ScopeLogger(); return media_content_scan_file(uri.c_str()); } PlatformResult ContentManager::scanDirectory(media_scan_completed_cb callback, ReplyCallbackData* cbData) { - LoggerD("Enter"); + ScopeLogger(); const std::string& contentDirURI = cbData->args.get("contentDirURI").get(); std::string real_path = common::FilesystemProvider::Create().GetRealPath(contentDirURI); const bool recursive = cbData->args.get("recursive").get(); @@ -866,7 +866,7 @@ PlatformResult ContentManager::scanDirectory(media_scan_completed_cb callback, } PlatformResult ContentManager::cancelScanDirectory(const std::string& content_dir_uri) { - LoggerD("Enter"); + ScopeLogger(); int ret = media_content_cancel_scan_folder(content_dir_uri.c_str()); if (ret != MEDIA_CONTENT_ERROR_NONE) { @@ -880,7 +880,7 @@ PlatformResult ContentManager::cancelScanDirectory(const std::string& content_di PlatformResult ContentManager::addChangeListener(media_content_noti_h* noti_handle, media_content_db_update_cb callback, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); int ret = media_content_add_db_updated_cb(callback, user_data, noti_handle); @@ -893,7 +893,7 @@ PlatformResult ContentManager::addChangeListener(media_content_noti_h* noti_hand } PlatformResult ContentManager::removeChangeListener(media_content_noti_h noti_handle) { - LoggerD("Enter"); + ScopeLogger(); int ret = media_content_remove_db_updated_cb(noti_handle); @@ -913,7 +913,7 @@ PlatformResult ContentManager::removeChangeListener(media_content_noti_h noti_ha PlatformResult ContentManager::setChangeListener(media_content_db_update_cb callback, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); int ret = media_content_set_db_updated_cb(callback, user_data); if (ret != MEDIA_CONTENT_ERROR_NONE) { @@ -925,7 +925,7 @@ PlatformResult ContentManager::setChangeListener(media_content_db_update_cb call } PlatformResult ContentManager::unSetChangeListener() { - LoggerD("Enter"); + ScopeLogger(); int ret = media_content_unset_db_updated_cb(); if (ret != MEDIA_CONTENT_ERROR_NONE) { @@ -938,7 +938,7 @@ PlatformResult ContentManager::unSetChangeListener() { void ContentManager::createPlaylist(std::string name, const std::shared_ptr& user_data) { - LoggerD("Enter"); + ScopeLogger(); media_playlist_h playlist = NULL; int ret = media_playlist_insert_to_db(name.c_str(), &playlist); @@ -1000,7 +1000,7 @@ void ContentManager::createPlaylist(std::string name, } void ContentManager::getPlaylists(const std::shared_ptr& user_data) { - LoggerD("Enter"); + ScopeLogger(); int ret; filter_h filter = nullptr; media_filter_create(&filter); @@ -1023,7 +1023,7 @@ void ContentManager::getPlaylists(const std::shared_ptr& user void ContentManager::removePlaylist(std::string playlistId, const std::shared_ptr& user_data) { - LoggerD("Enter"); + ScopeLogger(); int id = std::atoi(playlistId.c_str()); if (id == 0) { PlatformResult err = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "PlaylistId is wrong."); @@ -1040,7 +1040,7 @@ void ContentManager::removePlaylist(std::string playlistId, } int ContentManager::update(picojson::value args) { - LoggerD("Enter"); + ScopeLogger(); int ret; picojson::value content = args.get("content"); @@ -1058,7 +1058,7 @@ int ContentManager::update(picojson::value args) { } int ContentManager::updateBatch(picojson::value args) { - LoggerD("Enter"); + ScopeLogger(); int ret = 0; std::vector contents = args.get("contents").get(); @@ -1087,7 +1087,7 @@ int ContentManager::updateBatch(picojson::value args) { } int ContentManager::playlistAdd(std::string playlist_id, std::string content_id) { - LoggerD("Enter"); + ScopeLogger(); media_playlist_h playlist = NULL; int ret = media_playlist_get_playlist_from_db(std::stoi(playlist_id), &playlist); @@ -1111,7 +1111,7 @@ int ContentManager::playlistAdd(std::string playlist_id, std::string content_id) } int ContentManager::playlistRemove(std::string playlist_id, int member_id) { - LoggerD("Enter"); + ScopeLogger(); media_playlist_h playlist = NULL; int ret = media_playlist_get_playlist_from_db(std::stoi(playlist_id), &playlist); @@ -1134,7 +1134,7 @@ int ContentManager::playlistRemove(std::string playlist_id, int member_id) { } void ContentManager::playlistAddbatch(const std::shared_ptr& user_data) { - LoggerD("Enter"); + ScopeLogger(); std::string playlist_id = user_data->args.get("playlistId").get(); media_playlist_h playlist = NULL; @@ -1169,7 +1169,7 @@ void ContentManager::playlistAddbatch(const std::shared_ptr& } void ContentManager::playlistGet(const std::shared_ptr& user_data) { - LoggerD("Enter"); + ScopeLogger(); media_playlist_h playlist = NULL; media_content_order_e order = MEDIA_CONTENT_ORDER_ASC; const std::string playOrder("play_order"); @@ -1228,7 +1228,7 @@ void ContentManager::playlistGet(const std::shared_ptr& user_ } void ContentManager::playlistRemovebatch(const std::shared_ptr& user_data) { - LoggerD("Enter"); + ScopeLogger(); media_playlist_h playlist = NULL; SCOPE_EXIT { @@ -1268,7 +1268,7 @@ void ContentManager::playlistRemovebatch(const std::shared_ptr& user_data) { - LoggerD("Enter"); + ScopeLogger(); media_playlist_h playlist = NULL; SCOPE_EXIT { @@ -1326,7 +1326,7 @@ void ContentManager::playlistSetOrder(const std::shared_ptr& } void ContentManager::playlistMove(const std::shared_ptr& user_data) { - LoggerD("Enter"); + ScopeLogger(); media_playlist_h playlist = NULL; SCOPE_EXIT { @@ -1374,7 +1374,7 @@ void ContentManager::playlistMove(const std::shared_ptr& user } int ContentManager::getLyrics(const picojson::value& args, picojson::object& result) { - LoggerD("Enter"); + ScopeLogger(); int ret = METADATA_EXTRACTOR_ERROR_NONE; const std::string& contentURI = args.get("contentURI").to_str(); @@ -1442,7 +1442,7 @@ int ContentManager::getLyrics(const picojson::value& args, picojson::object& res } media_playlist_h getPlaylistHandle(int id) { - LoggerD("Entered"); + ScopeLogger(); media_playlist_h playlist_handle = nullptr; int ret_code = media_playlist_get_playlist_from_db(id, &playlist_handle); if (MEDIA_CONTENT_ERROR_NONE != ret_code || playlist_handle == nullptr) { @@ -1454,7 +1454,7 @@ media_playlist_h getPlaylistHandle(int id) { } void destroyMediaPlaylistHandle(media_playlist_h& playlist_handle) { - LoggerD("Entered"); + ScopeLogger(); if (playlist_handle) { int ret_code = media_playlist_destroy(playlist_handle); playlist_handle = nullptr; @@ -1466,7 +1466,7 @@ void destroyMediaPlaylistHandle(media_playlist_h& playlist_handle) { } int ContentManager::getPlaylistName(int id, std::string* result) { - LoggerD("Entered"); + ScopeLogger(); media_playlist_h playlist_handle = getPlaylistHandle(id); PlaylistUniquePtr playlist_ptr(playlist_handle, destroyMediaPlaylistHandle); @@ -1490,7 +1490,7 @@ int ContentManager::getPlaylistName(int id, std::string* result) { } int updatePlaylistInDB(media_playlist_h playlist_handle) { - LoggerD("Entered"); + ScopeLogger(); int ret_code = media_playlist_update_to_db(playlist_handle); if (MEDIA_CONTENT_ERROR_NONE != ret_code) { LoggerE("media_playlist_update_to_db failed"); @@ -1500,7 +1500,7 @@ int updatePlaylistInDB(media_playlist_h playlist_handle) { } int ContentManager::setPlaylistName(int id, const std::string& name) { - LoggerD("Entered"); + ScopeLogger(); if (name.empty()) { LoggerE("Cannot set empty playlist name!"); return MEDIA_CONTENT_ERROR_INVALID_PARAMETER; @@ -1532,7 +1532,7 @@ int ContentManager::setPlaylistName(int id, const std::string& name) { } int ContentManager::getThumbnailUri(int id, std::string* result) { - LoggerD("Entered"); + ScopeLogger(); media_playlist_h playlist_handle = getPlaylistHandle(id); PlaylistUniquePtr playlist_ptr(playlist_handle, destroyMediaPlaylistHandle); @@ -1560,7 +1560,7 @@ int ContentManager::getThumbnailUri(int id, std::string* result) { } int ContentManager::setThumbnailUri(int id, const std::string& thb_uri) { - LoggerD("Entered"); + ScopeLogger(); // Allow setting empty URI, unfortunately Core API does not allow to set empty // path so we need to set one empty space. This is probably issue of Core API. @@ -1586,7 +1586,7 @@ int ContentManager::setThumbnailUri(int id, const std::string& thb_uri) { } int ContentManager::getNumberOfTracks(int id, int* result) { - LoggerD("Entered"); + ScopeLogger(); int count = 0; const int ret_code = media_playlist_get_media_count_from_db(id, nullptr, &count); @@ -1601,7 +1601,7 @@ int ContentManager::getNumberOfTracks(int id, int* result) { } common::PlatformResult ContentManager::createThumbnail(const picojson::value& args) { - LoggerD("Enter"); + ScopeLogger(); unsigned int* callbackId = new unsigned int(static_cast(args.get("callbackId").get())); diff --git a/src/datacontrol/datacontrol_instance.cc b/src/datacontrol/datacontrol_instance.cc index 216d391..97c3720 100644 --- a/src/datacontrol/datacontrol_instance.cc +++ b/src/datacontrol/datacontrol_instance.cc @@ -60,6 +60,7 @@ struct DatacontrolInformation { static std::map IdMap; DatacontrolInstance::DatacontrolInstance() { + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; #define REGISTER_SYNC(c, x) \ @@ -78,11 +79,12 @@ DatacontrolInstance::DatacontrolInstance() { } DatacontrolInstance::~DatacontrolInstance() { + ScopeLogger(); } static void ReplyAsync(DatacontrolInstance* instance, int callbackId, bool isSuccess, picojson::object* param) { - LoggerD("Enter"); + ScopeLogger(); (*param)["callbackId"] = picojson::value(static_cast(callbackId)); (*param)["status"] = picojson::value(isSuccess ? "success" : "error"); @@ -92,7 +94,7 @@ static void ReplyAsync(DatacontrolInstance* instance, int callbackId, bool isSuc } static bool SQLColumnName(result_set_cursor cursor, int columnIndex, picojson::value& name) { - LoggerD("Enter"); + ScopeLogger(); char buffer[4096]; int result = data_control_sql_get_column_name(cursor, columnIndex, buffer); if (result != DATA_CONTROL_ERROR_NONE) { @@ -104,7 +106,7 @@ static bool SQLColumnName(result_set_cursor cursor, int columnIndex, picojson::v } static bool SQLColumnValue(result_set_cursor cursor, int columnIndex, picojson::value& val) { - LoggerD("Enter"); + ScopeLogger(); data_control_sql_column_type_e type = DATA_CONTROL_SQL_COLUMN_TYPE_UNDEFINED; int result = data_control_sql_get_column_item_type(cursor, columnIndex, &type); if (result != DATA_CONTROL_ERROR_NONE) { @@ -178,7 +180,7 @@ static bool SQLColumnValue(result_set_cursor cursor, int columnIndex, picojson:: static void MAPAddResponseCallback(int requestId, data_control_h handle, bool providerResult, const char* error, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); @@ -198,7 +200,7 @@ static void MAPAddResponseCallback(int requestId, data_control_h handle, bool pr static void MAPSetResponseCallback(int requestId, data_control_h handle, bool providerResult, const char* error, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); @@ -219,7 +221,7 @@ static void MAPSetResponseCallback(int requestId, data_control_h handle, bool pr static void MAPGetResponseCallback(int requestId, data_control_h handle, char** result_value_list, int result_value_count, bool providerResult, const char* error, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); @@ -245,7 +247,7 @@ static void MAPGetResponseCallback(int requestId, data_control_h handle, char** static void MAPRemoveReponseCallback(int requestId, data_control_h handle, bool providerResult, const char* error, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); @@ -266,7 +268,7 @@ static void MAPRemoveReponseCallback(int requestId, data_control_h handle, bool static void SQLSelectResponseCallback(int requestId, data_control_h handle, result_set_cursor cursor, bool providerResult, const char* error, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); @@ -307,7 +309,7 @@ static void SQLSelectResponseCallback(int requestId, data_control_h handle, static void SQLInsertResponseCallback(int requestId, data_control_h handle, long long inserted_row_id, bool providerResult, const char* error, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); @@ -329,7 +331,7 @@ static void SQLInsertResponseCallback(int requestId, data_control_h handle, static void SQLUpdateResponseCallback(int requestId, data_control_h handle, bool providerResult, const char* error, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); @@ -349,7 +351,7 @@ static void SQLUpdateResponseCallback(int requestId, data_control_h handle, bool static void SQLDeleteResponseCallback(int requestId, data_control_h handle, bool providerResult, const char* error, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); DatacontrolInformation* info = IdMap[requestId]; if (info == NULL) { LoggerE("Invalid context"); @@ -385,7 +387,7 @@ static data_control_map_response_cb mapResponseCallback = { int DatacontrolInstance::RunMAPDataControlJob(const std::string& providerId, const std::string& dataId, int callbackId, int userRequestId, DataControlJob job) { - LoggerD("Enter"); + ScopeLogger(); int result = DATA_CONTROL_ERROR_NONE; std::unique_ptr info{new DatacontrolInformation()}; info->callbackId = callbackId; @@ -420,7 +422,7 @@ int DatacontrolInstance::RunMAPDataControlJob(const std::string& providerId, int DatacontrolInstance::RunSQLDataControlJob(const std::string& providerId, const std::string& dataId, int callbackId, int userRequestId, DataControlJob job) { - LoggerD("Enter"); + ScopeLogger(); int result = DATA_CONTROL_ERROR_NONE; std::unique_ptr info{new DatacontrolInformation()}; info->callbackId = callbackId; @@ -461,7 +463,7 @@ int DatacontrolInstance::RunSQLDataControlJob(const std::string& providerId, void DatacontrolInstance::DataControlManagerGetdatacontrolconsumer(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "providerId", out) @@ -469,7 +471,7 @@ void DatacontrolInstance::DataControlManagerGetdatacontrolconsumer(const picojso } void DatacontrolInstance::SQLDataControlConsumerInsert(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "reqId", out) @@ -546,7 +548,7 @@ void DatacontrolInstance::SQLDataControlConsumerInsert(const picojson::value& ar } void DatacontrolInstance::SQLDataControlConsumerUpdate(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "reqId", out) @@ -576,7 +578,7 @@ void DatacontrolInstance::SQLDataControlConsumerUpdate(const picojson::value& ar int result = RunSQLDataControlJob( providerId, dataId, callbackId, reqId, [&updateData, &where](data_control_h& handle, int* requestId) -> int { - LoggerD("Enter"); + ScopeLogger(); picojson::array columns = updateData["columns"].get(); picojson::array values = updateData["values"].get(); @@ -624,7 +626,7 @@ void DatacontrolInstance::SQLDataControlConsumerUpdate(const picojson::value& ar void DatacontrolInstance::SQLDataControlConsumerRemove(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "reqId", out) @@ -661,7 +663,7 @@ void DatacontrolInstance::SQLDataControlConsumerRemove(const picojson::value& ar void DatacontrolInstance::SQLDataControlConsumerSelect(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "reqId", out) @@ -695,7 +697,7 @@ void DatacontrolInstance::SQLDataControlConsumerSelect(const picojson::value& ar int result = RunSQLDataControlJob( providerId, dataId, callbackId, reqId, [&columns, &where, order, page, maxNumberPerPage]( data_control_h& handle, int* requestId) -> int { - LoggerD("Enter"); + ScopeLogger(); std::vector temp; for (auto& s : columns) temp.push_back(s.get().c_str()); int columnCount = static_cast(temp.size()); @@ -727,7 +729,7 @@ void DatacontrolInstance::SQLDataControlConsumerSelect(const picojson::value& ar } void DatacontrolInstance::MappedDataControlConsumerAddvalue(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "reqId", out) @@ -767,7 +769,7 @@ void DatacontrolInstance::MappedDataControlConsumerAddvalue(const picojson::valu } void DatacontrolInstance::MappedDataControlConsumerRemovevalue(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "reqId", out) @@ -806,7 +808,7 @@ void DatacontrolInstance::MappedDataControlConsumerRemovevalue(const picojson::v } void DatacontrolInstance::MappedDataControlConsumerGetvalue(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "reqId", out) @@ -842,7 +844,7 @@ void DatacontrolInstance::MappedDataControlConsumerGetvalue(const picojson::valu } void DatacontrolInstance::MappedDataControlConsumerUpdatevalue(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeDatacontrol, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "reqId", out) diff --git a/src/download/download_instance.cc b/src/download/download_instance.cc index 208caae..5a1dd70 100644 --- a/src/download/download_instance.cc +++ b/src/download/download_instance.cc @@ -40,7 +40,7 @@ const std::string kPrivilegeDownload = "http://tizen.org/privilege/download"; } // namespace DownloadInstance::DownloadInstance() { - LoggerD("Entered"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; #define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&DownloadInstance::x, this, _1, _2)); @@ -59,7 +59,7 @@ DownloadInstance::DownloadInstance() { } DownloadInstance::~DownloadInstance() { - LoggerD("Entered"); + ScopeLogger(); int ret; for (DownloadCallbackMap::iterator it = download_callbacks.begin(); it != download_callbacks.end(); ++it) { @@ -99,7 +99,7 @@ DownloadInstance::~DownloadInstance() { } bool DownloadInstance::CheckInstance(DownloadInstance* instance) { - LoggerD("Entered"); + ScopeLogger(); for (auto vec_instance : instances_) { if (vec_instance == instance) { return true; @@ -184,7 +184,7 @@ common::PlatformResult DownloadInstance::convertError(int err, const std::string } void DownloadInstance::OnStateChanged(int download_id, download_state_e state, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); CallbackPtr downCbPtr = static_cast(user_data); downCbPtr->state = state; @@ -217,7 +217,7 @@ void DownloadInstance::OnStateChanged(int download_id, download_state_e state, v } gboolean DownloadInstance::OnProgressChanged(void* user_data) { - LoggerD("Entered"); + ScopeLogger(); CallbackPtr downCbPtr = static_cast(user_data); std::lock_guard lock(instances_mutex_); if (!CheckInstance(downCbPtr->instance)) { @@ -246,7 +246,7 @@ gboolean DownloadInstance::OnProgressChanged(void* user_data) { } void DownloadInstance::OnStart(int download_id, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); unsigned long long totalSize; CallbackPtr downCbPtr = static_cast(user_data); @@ -269,7 +269,7 @@ void DownloadInstance::OnStart(int download_id, void* user_data) { } gboolean DownloadInstance::OnFinished(void* user_data) { - LoggerD("Entered"); + ScopeLogger(); char* fullPath = NULL; CallbackPtr downCbPtr = static_cast(user_data); @@ -323,7 +323,7 @@ gboolean DownloadInstance::OnFinished(void* user_data) { } gboolean DownloadInstance::OnPaused(void* user_data) { - LoggerD("Entered"); + ScopeLogger(); CallbackPtr downCbPtr = static_cast(user_data); std::lock_guard lock(instances_mutex_); if (!CheckInstance(downCbPtr->instance)) { @@ -348,7 +348,7 @@ gboolean DownloadInstance::OnPaused(void* user_data) { } gboolean DownloadInstance::OnCanceled(void* user_data) { - LoggerD("Entered"); + ScopeLogger(); CallbackPtr downCbPtr = static_cast(user_data); std::lock_guard lock(instances_mutex_); if (!CheckInstance(downCbPtr->instance)) { @@ -391,7 +391,7 @@ gboolean DownloadInstance::OnCanceled(void* user_data) { } gboolean DownloadInstance::OnFailed(void* user_data) { - LoggerD("Entered"); + ScopeLogger(); download_error_e error; picojson::object out; @@ -451,7 +451,7 @@ gboolean DownloadInstance::OnFailed(void* user_data) { void DownloadInstance::progress_changed_cb(int download_id, long long unsigned received, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); CallbackPtr downCbPtr = static_cast(user_data); downCbPtr->received = received; downCbPtr->downloadId = download_id; @@ -460,7 +460,7 @@ void DownloadInstance::progress_changed_cb(int download_id, long long unsigned r } void DownloadInstance::DownloadManagerStart(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeDownload, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "url", out) @@ -643,7 +643,7 @@ void DownloadInstance::DownloadManagerStart(const picojson::value& args, picojso } void DownloadInstance::DownloadManagerCancel(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, "downloadId", out) int downloadId, ret; @@ -668,7 +668,7 @@ void DownloadInstance::DownloadManagerCancel(const picojson::value& args, picojs } void DownloadInstance::DownloadManagerPause(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, "downloadId", out) int downloadId, ret; @@ -693,7 +693,7 @@ void DownloadInstance::DownloadManagerPause(const picojson::value& args, picojso } void DownloadInstance::DownloadManagerResume(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, "downloadId", out) int downloadId, ret; @@ -718,7 +718,7 @@ void DownloadInstance::DownloadManagerResume(const picojson::value& args, picojs } void DownloadInstance::DownloadManagerGetstate(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, "downloadId", out) int downloadId, ret; std::string stateValue; @@ -772,7 +772,7 @@ void DownloadInstance::DownloadManagerGetstate(const picojson::value& args, pico void DownloadInstance::DownloadManagerGetmimetype(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, "downloadId", out) int downloadId, ret; @@ -800,7 +800,7 @@ void DownloadInstance::DownloadManagerGetmimetype(const picojson::value& args, } bool DownloadInstance::GetDownloadID(const int callback_id, int& download_id) { - LoggerD("Entered"); + ScopeLogger(); if (diMap.find(callback_id) != diMap.end()) { download_id = diMap.find(callback_id)->second->download_id; } else { @@ -811,13 +811,13 @@ bool DownloadInstance::GetDownloadID(const int callback_id, int& download_id) { void DownloadInstance::DownloadManagerGetdownloadrequest(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); // Nothing to do } void DownloadInstance::DownloadManagerSetlistener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); // Nothing to do } diff --git a/src/exif/exif_gps_location.cc b/src/exif/exif_gps_location.cc index 2426cb0..23da8c5 100644 --- a/src/exif/exif_gps_location.cc +++ b/src/exif/exif_gps_location.cc @@ -27,16 +27,16 @@ namespace extension { namespace exif { GCSPosition::GCSPosition() { - LoggerD("Enter"); + ScopeLogger(); } GCSPosition::GCSPosition(Rational _degrees, Rational _minutes, Rational _seconds) : degrees(_degrees), minutes(_minutes), seconds(_seconds) { - LoggerD("Enter"); + ScopeLogger(); } bool GCSPosition::isValid() const { - LoggerD("Enter"); + ScopeLogger(); if (!(degrees.isValid() && minutes.isValid() && seconds.isValid())) { return false; } @@ -50,7 +50,7 @@ bool GCSPosition::isValid() const { } double GCSPosition::toDouble() const { - LoggerD("Enter"); + ScopeLogger(); const double degrees_value = degrees.toDouble(); const double minutes_value = minutes.toDouble(); const double seconds_value = seconds.toDouble(); @@ -58,7 +58,7 @@ double GCSPosition::toDouble() const { } Rationals GCSPosition::toRationalsVector() const { - LoggerD("Enter"); + ScopeLogger(); Rationals vec; vec.push_back(degrees); vec.push_back(minutes); @@ -67,7 +67,7 @@ Rationals GCSPosition::toRationalsVector() const { } std::string GCSPosition::toDebugString() const { - LoggerD("Enter"); + ScopeLogger(); std::stringstream ss; ss << degrees.toString() << "d "; ss << minutes.toString() << "m "; @@ -76,7 +76,7 @@ std::string GCSPosition::toDebugString() const { } GCSPosition GCSPosition::createFromDouble(double value) { - LoggerD("Entered value:%f"); + ScopeLogger("value: %f", value); if (value < 0) { LoggerW("Trying to create GCSPosition with double < 0: %f", value); return GCSPosition(); @@ -120,14 +120,14 @@ GCSPosition GCSPosition::createFromDouble(double value) { ExifGPSLocation::ExifGPSLocation() : m_longitude_ref(GPS_LOCATION_WEST), m_latitude_ref(GPS_LOCATION_NORTH) { for (int i = 0; i < EXIF_GPS_LOCATION_ATTRIBUTE_NUMBER_OF_ATTRIBUTES; ++i) { - LoggerD("Enter"); + ScopeLogger(); m_is_set[i] = false; } LoggerE("ExifGPSLocation::ExifGPSLocation()"); } ExifGPSLocation::ExifGPSLocation(double longitude, double latitude) { - LoggerD("Enter"); + ScopeLogger(); for (int i = 0; i < EXIF_GPS_LOCATION_ATTRIBUTE_NUMBER_OF_ATTRIBUTES; ++i) { m_is_set[i] = false; } @@ -149,7 +149,7 @@ ExifGPSLocation::ExifGPSLocation(double longitude, double latitude) { } void ExifGPSLocation::setLongitude(const GCSPosition& longitude) { - LoggerD("Enter"); + ScopeLogger(); if (!longitude.isValid()) { LoggerW("longitude is not valid!"); return; @@ -160,23 +160,23 @@ void ExifGPSLocation::setLongitude(const GCSPosition& longitude) { } const GCSPosition& ExifGPSLocation::getLongitude() const { - LoggerD("Enter"); + ScopeLogger(); return m_longitude; } void ExifGPSLocation::setLongitudeRef(GPSLocationDirectionLongitude ref) { - LoggerD("Enter"); + ScopeLogger(); m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE_REF] = true; m_longitude_ref = ref; } GPSLocationDirectionLongitude ExifGPSLocation::getLongitudeRef() const { - LoggerD("Enter"); + ScopeLogger(); return m_longitude_ref; } void ExifGPSLocation::setLatitude(const GCSPosition& latitude) { - LoggerD("Enter"); + ScopeLogger(); if (!latitude.isValid()) { LoggerW("latitude is not valid!"); return; @@ -187,33 +187,33 @@ void ExifGPSLocation::setLatitude(const GCSPosition& latitude) { } const GCSPosition& ExifGPSLocation::getLatitude() const { - LoggerD("Enter"); + ScopeLogger(); return m_latitude; } void ExifGPSLocation::setLatitudeRef(GPSLocationDirectionLatitude ref) { - LoggerD("Enter"); + ScopeLogger(); m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE_REF] = true; m_latitude_ref = ref; } GPSLocationDirectionLatitude ExifGPSLocation::getLatitudeRef() const { - LoggerD("Enter"); + ScopeLogger(); return m_latitude_ref; } bool ExifGPSLocation::isSet(ExifGPSLocationAttributes attribute) const { - LoggerD("Enter"); + ScopeLogger(); return m_is_set[attribute]; } void ExifGPSLocation::unset(ExifGPSLocationAttributes attribute) { - LoggerD("Enter"); + ScopeLogger(); m_is_set[attribute] = false; } void ExifGPSLocation::unsetAll() { - LoggerD("Enter"); + ScopeLogger(); m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE] = false; m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE_REF] = false; m_longitude = GCSPosition(); @@ -224,7 +224,7 @@ void ExifGPSLocation::unsetAll() { } bool ExifGPSLocation::isComplete() const { - LoggerD("Enter"); + ScopeLogger(); return m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE] && m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LONGITUDE_REF] && m_is_set[EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE] && @@ -232,19 +232,19 @@ bool ExifGPSLocation::isComplete() const { } bool ExifGPSLocation::isValid() const { - LoggerD("Enter"); + ScopeLogger(); return isComplete() && m_latitude.isValid() && m_longitude.isValid(); } double ExifGPSLocation::getLongitudeValue() const { - LoggerD("Enter"); + ScopeLogger(); const double longitude_dir = (m_longitude_ref == GPS_LOCATION_WEST) ? -1.0f : 1.0f; const double longitude = m_longitude.toDouble() * longitude_dir; return longitude; } double ExifGPSLocation::getLatitudeValue() const { - LoggerD("Enter"); + ScopeLogger(); const double latitude_dir = (m_latitude_ref == GPS_LOCATION_SOUTH) ? -1.0f : 1.0f; const double latitude = m_latitude.toDouble() * latitude_dir; return latitude; diff --git a/src/exif/exif_information.cc b/src/exif/exif_information.cc index 08f7ed9..90cdb1a 100644 --- a/src/exif/exif_information.cc +++ b/src/exif/exif_information.cc @@ -50,7 +50,7 @@ constexpr unsigned int str2int(const char* str, int h = 0) { } IsoSpeedRatingsVector jsonArray2vector(const picojson::value& a) { - LoggerD("Enter"); + ScopeLogger(); if (!a.is()) { return IsoSpeedRatingsVector(); } @@ -68,14 +68,14 @@ IsoSpeedRatingsVector jsonArray2vector(const picojson::value& a) { } // namespace ExifInformation::ExifInformation() { - LoggerD("Enter"); + ScopeLogger(); for (int attr = 0; attr < EXIF_INFORMATION_ATTRIBUTE_NUMBER_OF_ATTRIBUTES; attr++) { unset(static_cast(attr)); } } ExifInformation::ExifInformation(const picojson::value& args) { - LoggerD("Enter"); + ScopeLogger(); for (int attr = 0; attr < EXIF_INFORMATION_ATTRIBUTE_NUMBER_OF_ATTRIBUTES; attr++) { unset(static_cast(attr)); } @@ -91,104 +91,87 @@ ExifInformation::ExifInformation(const picojson::value& args) { } ExifInformation::~ExifInformation() { - LoggerD("Enter"); + ScopeLogger(); } const std::string& ExifInformation::getUri() { - LoggerD("Entered"); return m_uri; } void ExifInformation::setUri(const std::string& uri) { - LoggerD("Entered"); - LoggerD("URI: %s", uri.c_str()); m_is_set[EXIF_INFORMATION_ATTRIBUTE_URI] = true; m_uri = uri; + LoggerD("URI: %s", uri.c_str()); } unsigned long ExifInformation::getWidth() const { - LoggerD("Entered"); return m_width; } void ExifInformation::setWidth(unsigned long width) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_WIDTH] = true; m_width = width; } unsigned long ExifInformation::getHeight() const { - LoggerD("Entered"); return m_height; } void ExifInformation::setHeight(unsigned long height) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_HEIGHT] = true; m_height = height; } const std::string& ExifInformation::getDeviceMaker() { - LoggerD("Entered"); return m_device_maker; } void ExifInformation::setDeviceMaker(const std::string& device_maker) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_DEVICE_MAKER] = true; m_device_maker = device_maker; } const std::string& ExifInformation::getDeviceModel() { - LoggerD("Entered"); return m_device_model; } void ExifInformation::setDeviceModel(const std::string& device_model) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_DEVICE_MODEL] = true; m_device_model = device_model; } time_t ExifInformation::getOriginalTime() const { - LoggerD("Entered"); return m_original_time; } void ExifInformation::setOriginalTime(time_t original_time) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_ORIGINAL_TIME] = true; m_original_time = original_time; } const std::string& ExifInformation::getOrientationString() { - LoggerD("Entered"); return ExifUtil::orientationToString(m_orientation); } ImageOrientation ExifInformation::getOrientation() { - LoggerD("Entered"); return m_orientation; } void ExifInformation::setOrientation(const std::string& orientation) { - LoggerD("Entered"); + ScopeLogger(); setOrientation(ExifUtil::stringToOrientation(orientation)); } void ExifInformation::setOrientation(ImageOrientation orientation) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_ORIENTATION] = true; m_orientation = orientation; } const Rational& ExifInformation::getFNumber() const { - LoggerD("Entered"); return m_f_number; } void ExifInformation::setFNumber(Rational f_number) { - LoggerD("Entered"); if (!f_number.isValid()) { LoggerW("Trying to set invalid F-Number: %s", f_number.toString().c_str()); return; @@ -199,23 +182,19 @@ void ExifInformation::setFNumber(Rational f_number) { } const std::vector& ExifInformation::getIsoSpeedRatings() { - LoggerD("Entered"); return m_iso_speed_ratings; } void ExifInformation::setIsoSpeedRatings(const std::vector& iso_speed_ratings) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_ISO_SPEED_RATINGS] = true; m_iso_speed_ratings = iso_speed_ratings; } const Rational& ExifInformation::getExposureTime() { - LoggerD("Entered"); return m_exposure_time; } void ExifInformation::setExposureTime(const Rational& exposure_time) { - LoggerD("Entered"); if (!exposure_time.isValid() || 0 == exposure_time.nominator) { LoggerW("Trying to set invalid exposure time: [%s]", exposure_time.toString().c_str()); return; @@ -226,45 +205,39 @@ void ExifInformation::setExposureTime(const Rational& exposure_time) { } const std::string& ExifInformation::getExposureProgramString() { - LoggerD("Entered"); + ScopeLogger(); return ExifUtil::exposureProgramToString(m_exposure_program); ; } ExposureProgram ExifInformation::getExposureProgram() { - LoggerD("Entered"); return m_exposure_program; } void ExifInformation::setExposureProgram(const std::string& exposure_program) { - LoggerD("Entered"); + ScopeLogger(); setExposureProgram(ExifUtil::stringToExposureProgram(exposure_program)); } void ExifInformation::setExposureProgram(ExposureProgram exposure_program) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_EXPOSURE_PROGRAM] = true; m_exposure_program = exposure_program; } bool ExifInformation::getFlash() const { - LoggerD("Entered"); return m_flash; } void ExifInformation::setFlash(bool flash) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_FLASH] = true; m_flash = flash; } const Rational& ExifInformation::getFocalLength() const { - LoggerD("Entered"); return m_focal_length; } void ExifInformation::setFocalLength(Rational focal_length) { - LoggerD("Entered"); if (!focal_length.isValid()) { LoggerW("Trying to set invalid focal length: %s", focal_length.toString().c_str()); return; @@ -275,50 +248,42 @@ void ExifInformation::setFocalLength(Rational focal_length) { } const std::string& ExifInformation::getWhiteBalanceModeString() { - LoggerD("Entered"); return ExifUtil::whiteBalanceToString(m_white_balance); } WhiteBalanceMode ExifInformation::getWhiteBalanceMode() { - LoggerD("Entered"); return m_white_balance; } void ExifInformation::setWhiteBalanceMode(const std::string& white_balance) { - LoggerD("Entered"); + ScopeLogger(); setWhiteBalanceMode(ExifUtil::stringToWhiteBalance(white_balance)); } void ExifInformation::setWhiteBalanceMode(WhiteBalanceMode white_balance) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_WHITE_BALANCE] = true; m_white_balance = white_balance; } ExifGPSLocation& ExifInformation::getGPSExifLocation() { - LoggerD("Entered"); return m_gps_location; } void ExifInformation::setGPSLocation(ExifGPSLocation gps_location) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_GPS_LOCATION] = true; m_gps_location = gps_location; } void ExifInformation::unsetGPSLocation() { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_GPS_LOCATION] = false; m_gps_location.unsetAll(); } const Rational& ExifInformation::getGpsAltitude() const { - LoggerD("Entered"); return m_gps_altitude; } void ExifInformation::setGpsAltitude(Rational gps_altitude) { - LoggerD("Entered"); if (!gps_altitude.isValid()) { LoggerW("Trying to set invalid gps altitude: %s", gps_altitude.toString().c_str()); return; @@ -329,18 +294,16 @@ void ExifInformation::setGpsAltitude(Rational gps_altitude) { } GpsAltitudeRef ExifInformation::getGpsAltitudeRef() const { - LoggerD("Entered"); return m_gps_altitude_ref; } void ExifInformation::setGpsAltitudeRef(const GpsAltitudeRef ref) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_GPS_ALTITUDE_REF] = true; m_gps_altitude_ref = ref; } void ExifInformation::setGpsAltitudeWithRef(double gps_altitude) { - LoggerD("Entered"); + ScopeLogger(); setGpsAltitude(Rational::createFromDouble(fabs(gps_altitude))); if (gps_altitude >= 0.0) { @@ -351,8 +314,6 @@ void ExifInformation::setGpsAltitudeWithRef(double gps_altitude) { } double ExifInformation::getGpsAltitudeWithRef() const { - LoggerD("Entered"); - if (!m_is_set[EXIF_INFORMATION_ATTRIBUTE_GPS_ALTITUDE_REF] || GPS_ALTITUDE_REF_ABOVE_SEA == m_gps_altitude_ref) { return m_gps_altitude.toDouble(); @@ -362,18 +323,15 @@ double ExifInformation::getGpsAltitudeWithRef() const { } const std::string& ExifInformation::getGpsProcessingMethod() const { - LoggerD("Entered"); return m_gps_processing_method; } const std::string& ExifInformation::getGpsProcessingMethodType() const { - LoggerD("Entered"); return m_gps_processing_method_type; } void ExifInformation::setGpsProcessingMethod(const std::string& type, const std::string& processing_method) { - LoggerD("Entered"); if (type != EXIF_UNDEFINED_TYPE_ASCII && type != EXIF_UNDEFINED_TYPE_JIS && type != EXIF_UNDEFINED_TYPE_UNICODE && type != EXIF_UNDEFINED_TYPE_UNDEFINED) { LoggerW("Trying to set invalid GPSProcessingMethod type: [%s] len:%d", type.c_str(), @@ -387,34 +345,28 @@ void ExifInformation::setGpsProcessingMethod(const std::string& type, } void ExifInformation::setGpsTime(time_t time) { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_GPS_TIME] = true; m_gps_time = time; } time_t ExifInformation::getGpsTime() { - LoggerD("Entered"); return m_gps_time; } void ExifInformation::unsetGPStime() { - LoggerD("Entered"); m_is_set[EXIF_INFORMATION_ATTRIBUTE_GPS_TIME] = false; m_gps_time = 0; } const std::string& ExifInformation::getUserComment() { - LoggerD("Entered"); return m_user_comment; } const std::string& ExifInformation::getUserCommentType() { - LoggerD("Entered"); return m_user_comment_type; } void ExifInformation::setUserComment(const std::string& type, const std::string& user_comment) { - LoggerD("Entered"); if (type != EXIF_UNDEFINED_TYPE_ASCII && type != EXIF_UNDEFINED_TYPE_JIS && type != EXIF_UNDEFINED_TYPE_UNICODE && type != EXIF_UNDEFINED_TYPE_UNDEFINED) { LoggerW("Trying to set invalid user comment type: [%s] len:%d", type.c_str(), type.length()); @@ -427,12 +379,10 @@ void ExifInformation::setUserComment(const std::string& type, const std::string& } bool ExifInformation::isSet(ExifInformationAttribute attribute) const { - LoggerD("Entered"); return m_is_set[attribute]; } void ExifInformation::unset(ExifInformationAttribute attribute) { - LoggerD("Entered"); if (attribute >= EXIF_INFORMATION_ATTRIBUTE_NUMBER_OF_ATTRIBUTES) { return; } @@ -507,7 +457,7 @@ void ExifInformation::unset(ExifInformationAttribute attribute) { } void ExifInformation::set(std::string attributeName, const picojson::value& v) { - LoggerD("Entered | name: %s", attributeName.c_str()); + ScopeLogger(attributeName); switch (str2int(attributeName.c_str())) { case str2int(EI_URI): { @@ -593,7 +543,7 @@ void ExifInformation::set(std::string attributeName, const picojson::value& v) { } void ExifInformation::removeNulledAttributesFromExifData(ExifData* exif_data) { - LoggerD("Entered"); + ScopeLogger(); AssertMsg(exif_data, "exif_data is NULL"); if (!isSet(EXIF_INFORMATION_ATTRIBUTE_WIDTH)) { @@ -691,7 +641,7 @@ void ExifInformation::removeNulledAttributesFromExifData(ExifData* exif_data) { } PlatformResult ExifInformation::updateAttributesInExifData(ExifData* exif_data) { - LoggerD("Entered"); + ScopeLogger(); common::PlatformResult ret(common::ErrorCode::NO_ERROR); @@ -882,8 +832,7 @@ PlatformResult ExifInformation::updateAttributesInExifData(ExifData* exif_data) } PlatformResult ExifInformation::saveToFile(const std::string& file_path) { - LoggerD("Entered"); - LoggerD("Using JpegFile to read: [%s] and Exif if present", file_path.c_str()); + ScopeLogger("Using JpegFile to read: [%s] and Exif if present", file_path.c_str()); JpegFilePtr jpg_file; PlatformResult result = JpegFile::loadFile(file_path, &jpg_file); diff --git a/src/exif/exif_instance.cc b/src/exif/exif_instance.cc index ced9129..121390c 100644 --- a/src/exif/exif_instance.cc +++ b/src/exif/exif_instance.cc @@ -40,6 +40,7 @@ using common::PlatformResult; using common::ErrorCode; ExifInstance::ExifInstance() { + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -51,15 +52,17 @@ ExifInstance::ExifInstance() { } ExifInstance::~ExifInstance() { + ScopeLogger(); } void ExifInstance::ExifManagerGetExifInfo(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); const std::string& uri = args.get("uri").get(); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); JsonValue result = JsonValue(JsonObject()); PlatformResult status(ErrorCode::NO_ERROR); @@ -81,6 +84,7 @@ void ExifInstance::ExifManagerGetExifInfo(const picojson::value& args, picojson: }; auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(this, response->serialize().c_str()); @@ -89,15 +93,14 @@ void ExifInstance::ExifManagerGetExifInfo(const picojson::value& args, picojson: auto data = std::shared_ptr(new JsonValue(JsonObject())); common::TaskQueue::GetInstance().Queue(get, get_response, data); - - LoggerD("exit"); } void ExifInstance::ExifManagerSaveExifInfo(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); JsonValue result = JsonValue(JsonObject()); PlatformResult status(ErrorCode::NO_ERROR); @@ -113,6 +116,7 @@ void ExifInstance::ExifManagerSaveExifInfo(const picojson::value& args, picojson }; auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(this, response->serialize().c_str()); @@ -124,11 +128,12 @@ void ExifInstance::ExifManagerSaveExifInfo(const picojson::value& args, picojson } void ExifInstance::ExifManagerGetThumbnail(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const std::string& uri = args.get("uri").get(); const double callback_id = args.get("callbackId").get(); auto get = [=](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get"); PlatformResult status(ErrorCode::NO_ERROR); const std::string& file_path = ExifUtil::convertUriToPath(uri); @@ -188,6 +193,7 @@ void ExifInstance::ExifManagerGetThumbnail(const picojson::value& args, picojson }; auto get_response = [callback_id, this](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(this, response->serialize().c_str()); diff --git a/src/exif/exif_tag_saver.cc b/src/exif/exif_tag_saver.cc index 11bab29..7ead390 100644 --- a/src/exif/exif_tag_saver.cc +++ b/src/exif/exif_tag_saver.cc @@ -28,7 +28,7 @@ namespace extension { namespace exif { void ExifTagSaver::removeExifEntryWithTag(const ExifTag tag, ExifData* exif_data) { - LoggerD("Entered tag:%d (0x%x)", tag, tag); + ScopeLogger("tag:%d (0x%x)", tag, exif_data); ExifEntry* exif_entry = exif_data_get_entry(exif_data, tag); if (!exif_entry) { LoggerE("Exif entry with tag:%d (0x%x) is not present", tag, tag); @@ -39,7 +39,7 @@ void ExifTagSaver::removeExifEntryWithTag(const ExifTag tag, ExifData* exif_data } common::PlatformResult ExifTagSaver::saveToExif(long int value, ExifTag tag, ExifData* exif_data) { - LoggerD("Entered"); + ScopeLogger(); ExifEntry* entry = prepareEntry(exif_data, tag); if (!entry) { @@ -79,7 +79,7 @@ common::PlatformResult ExifTagSaver::saveToExif(long int value, ExifTag tag, Exi common::PlatformResult ExifTagSaver::saveToExif(const std::string& value, ExifTag tag, ExifData* exif_data, ExifFormat format, bool add_zero_character) { - LoggerD("Entered"); + ScopeLogger(); ExifEntry* entry = prepareEntry(exif_data, tag); if (!entry) { return LogAndCreateResult(common::ErrorCode::UNKNOWN_ERR, "Exif entry is null"); @@ -115,7 +115,7 @@ common::PlatformResult ExifTagSaver::saveToExif(const std::string& value, ExifTa common::PlatformResult ExifTagSaver::saveToExif(const Rational& value, ExifTag tag, ExifData* exif_data) { - LoggerD("Entered"); + ScopeLogger(); ExifEntry* entry = prepareEntry(exif_data, tag); if (!entry) { return LogAndCreateResult(common::ErrorCode::UNKNOWN_ERR, "Exif entry is null"); @@ -149,7 +149,7 @@ common::PlatformResult ExifTagSaver::saveToExif(const Rational& value, ExifTag t common::PlatformResult ExifTagSaver::saveToExif(const Rationals& value, ExifTag tag, ExifData* exif_data) { - LoggerD("Entered"); + ScopeLogger(); ExifEntry* entry = prepareEntry(exif_data, tag); if (!entry) { return LogAndCreateResult(common::ErrorCode::UNKNOWN_ERR, "Exif entry is null"); @@ -186,7 +186,7 @@ common::PlatformResult ExifTagSaver::saveToExif(const Rationals& value, ExifTag common::PlatformResult ExifTagSaver::saveToExif(std::vector& value, ExifFormat store_as, ExifTag tag, ExifData* exif_data) { - LoggerD("Entered"); + ScopeLogger(); ExifEntry* entry = prepareEntry(exif_data, tag); if (!entry) { return LogAndCreateResult(common::ErrorCode::UNKNOWN_ERR, "Exif entry is null"); @@ -274,7 +274,7 @@ common::PlatformResult ExifTagSaver::saveGpsLocationToExif(const ExifGPSLocation ExifData* exif_data) { common::PlatformResult ret(common::ErrorCode::NO_ERROR); - LoggerD("Entered"); + ScopeLogger(); if (gps_info.isSet(EXIF_GPS_LOCATION_ATTRIBUTE_LATITUDE)) { auto latitude = gps_info.getLatitude(); LoggerD("Saving latitude: %s", latitude.toDebugString().c_str()); @@ -319,7 +319,7 @@ common::PlatformResult ExifTagSaver::saveGpsLocationToExif(const ExifGPSLocation } ExifEntry* ExifTagSaver::prepareEntry(ExifData* exif_data, ExifTag tag) { - LoggerD("Entered m_tag:%d", tag); + ScopeLogger("tag:%d (0x%x)", tag, exif_data); ExifEntry* exif_entry = exif_data_get_entry(exif_data, tag); if (!exif_entry) { @@ -351,7 +351,7 @@ ExifEntry* ExifTagSaver::prepareEntry(ExifData* exif_data, ExifTag tag) { ExifEntry* ExifTagSaver::createNewTag(ExifData* exif_data, ExifIfd ifd, ExifFormat format, ExifTag tag) { - LoggerD("Creating new tag: %d", tag); + ScopeLogger("Creating new tag: %d", tag); ExifEntry* new_entry = exif_entry_new(); if (new_entry == nullptr) { @@ -366,7 +366,7 @@ ExifEntry* ExifTagSaver::createNewTag(ExifData* exif_data, ExifIfd ifd, ExifForm } common::PlatformResult ExifTagSaver::deduceIfdSection(ExifTag tag, ExifIfd* exif_ifd) { - LoggerD("Entered"); + ScopeLogger(); switch (static_cast(tag)) { // Tags in IFD_0 Section @@ -414,7 +414,7 @@ common::PlatformResult ExifTagSaver::deduceIfdSection(ExifTag tag, ExifIfd* exif } common::PlatformResult ExifTagSaver::deduceDataFormat(ExifTag tag, ExifFormat* exif_format) { - LoggerD("Entered"); + ScopeLogger(); switch (static_cast(tag)) { // Tags with byte type: diff --git a/src/exif/exif_util.cc b/src/exif/exif_util.cc index 9f9bc90..6b13004 100644 --- a/src/exif/exif_util.cc +++ b/src/exif/exif_util.cc @@ -72,13 +72,15 @@ const ExifByte ExifTypeInfo::SLongId = 9; const ExifByte ExifTypeInfo::SRationalId = 10; ExifUtil::ExifUtil() { + ScopeLogger(); } ExifUtil::~ExifUtil() { + ScopeLogger(); } ImageOrientation ExifUtil::stringToOrientation(const std::string& orientation) { - LoggerD("Entered"); + ScopeLogger(); if (ORIENTATION_NORMAL == orientation) { return ImageOrientation::EXIF_ORIENTATION_NORMAL; } @@ -107,7 +109,7 @@ ImageOrientation ExifUtil::stringToOrientation(const std::string& orientation) { } const std::string& ExifUtil::orientationToString(ImageOrientation orientation) { - LoggerD("Entered"); + ScopeLogger(); switch (orientation) { case ImageOrientation::EXIF_ORIENTATION_NORMAL: return ORIENTATION_NORMAL; @@ -131,7 +133,7 @@ const std::string& ExifUtil::orientationToString(ImageOrientation orientation) { } WhiteBalanceMode ExifUtil::stringToWhiteBalance(const std::string& white_balance) { - LoggerD("Entered"); + ScopeLogger(); if (WHITE_BALANCE_MODE_AUTO == white_balance) { return WhiteBalanceMode::EXIF_WHITE_BALANCE_MODE_AUTO; } @@ -142,7 +144,7 @@ WhiteBalanceMode ExifUtil::stringToWhiteBalance(const std::string& white_balance } const std::string& ExifUtil::whiteBalanceToString(WhiteBalanceMode value) { - LoggerD("Entered"); + ScopeLogger(); switch (value) { case WhiteBalanceMode::EXIF_WHITE_BALANCE_MODE_AUTO: return WHITE_BALANCE_MODE_AUTO; @@ -154,7 +156,7 @@ const std::string& ExifUtil::whiteBalanceToString(WhiteBalanceMode value) { } ExposureProgram ExifUtil::stringToExposureProgram(const std::string& exposure_program) { - LoggerD("Entered"); + ScopeLogger(); if (EXPOSURE_PROGRAM_NOT_DEFINED == exposure_program) { return EXIF_EXPOSURE_PROGRAM_NOT_DEFINED; } @@ -186,7 +188,7 @@ ExposureProgram ExifUtil::stringToExposureProgram(const std::string& exposure_pr } const std::string& ExifUtil::exposureProgramToString(ExposureProgram value) { - LoggerD("Entered"); + ScopeLogger(); switch (value) { case ExposureProgram::EXIF_EXPOSURE_PROGRAM_NOT_DEFINED: return EXPOSURE_PROGRAM_NOT_DEFINED; @@ -215,6 +217,7 @@ const std::string& ExifUtil::exposureProgramToString(ExposureProgram value) { // in: uri = file://TZ_USER_IMAGES/exif.jpg // out: path = TZ_USER_IMAGES/exif.jpg std::string ExifUtil::convertUriToPath(const std::string& str) { + ScopeLogger(); std::string path = ltrim(str); std::string prefix = path.substr(0, URI_PREFIX.size()); @@ -226,6 +229,7 @@ std::string ExifUtil::convertUriToPath(const std::string& str) { } std::string ExifUtil::ltrim(const std::string& s) { + ScopeLogger(); std::string str = s; std::string::iterator i; for (i = str.begin(); i != str.end(); ++i) { @@ -243,6 +247,7 @@ std::string ExifUtil::ltrim(const std::string& s) { } time_t ExifUtil::exifDateTimeOriginalToTimeT(const char* string) { + ScopeLogger(); int year, month, day, hour, min, sec; if (sscanf(string, "%5d:%5d:%5d %5d:%5d:%5d", &year, &month, &day, &hour, &min, &sec) >= 6) { return convertToTimeT(year, month, day, hour, min, sec); @@ -252,6 +257,7 @@ time_t ExifUtil::exifDateTimeOriginalToTimeT(const char* string) { } std::string ExifUtil::timeTToExifDateTimeOriginal(time_t time) { + ScopeLogger(); int year, month, day, hour, min, sec; extractFromTimeT(time, year, month, day, hour, min, sec); @@ -267,6 +273,7 @@ std::string ExifUtil::timeTToExifDateTimeOriginal(time_t time) { } const Rationals ExifUtil::timeTToExifGpsTimeStamp(time_t time) { + ScopeLogger(); int year, month, day, hour, min, sec; extractFromTimeT(time, year, month, day, hour, min, sec); @@ -283,6 +290,7 @@ const Rationals ExifUtil::timeTToExifGpsTimeStamp(time_t time) { } std::string ExifUtil::timeTToExifGpsDateStamp(time_t time) { + ScopeLogger(); int year, month, day, hour, min, sec; extractFromTimeT(time, year, month, day, hour, min, sec); @@ -301,6 +309,7 @@ std::string ExifUtil::timeTToExifGpsDateStamp(time_t time) { } size_t ExifUtil::getSizeOfExifFormatType(ExifFormat format) { + ScopeLogger(); std::size_t size_per_member = 0; switch (format) { case EXIF_FORMAT_BYTE: @@ -331,6 +340,7 @@ size_t ExifUtil::getSizeOfExifFormatType(ExifFormat format) { } void ExifUtil::printExifEntryInfo(ExifEntry* entry, ExifData* exif_data) { + ScopeLogger(); char buf[2000]; std::stringstream ss; @@ -372,6 +382,7 @@ void ExifUtil::printExifEntryInfo(ExifEntry* entry, ExifData* exif_data) { void ExifUtil::extractFromTimeT(const time_t time, int& out_year, int& out_month, int& out_day, int& out_hour, int& out_min, int& out_sec) { + ScopeLogger(); struct tm utc; gmtime_r(&time, &utc); @@ -384,6 +395,7 @@ void ExifUtil::extractFromTimeT(const time_t time, int& out_year, int& out_month } time_t ExifUtil::convertToTimeT(int year, int month, int day, int hour, int min, int sec) { + ScopeLogger(); struct tm timeinfo = {0}; time_t tmp_time = 0; tzset(); diff --git a/src/exif/get_exif_info.cc b/src/exif/get_exif_info.cc index 0c2efe0..e80f8f0 100644 --- a/src/exif/get_exif_info.cc +++ b/src/exif/get_exif_info.cc @@ -38,7 +38,7 @@ struct ExifDataHolder { }; Rational GetRationalFromEntry(ExifEntry* entry, ExifData* exif_data) { - LoggerD("Entered"); + ScopeLogger(); if (EXIF_FORMAT_RATIONAL == entry->format && entry->components >= 1 && entry->data) { const ExifByteOrder order = exif_data_get_byte_order(exif_data); return Rational(exif_get_rational(entry->data, order)); @@ -49,7 +49,7 @@ Rational GetRationalFromEntry(ExifEntry* entry, ExifData* exif_data) { bool GetRationalsFromEntry(ExifEntry* entry, ExifData* exif_data, unsigned long required_count, Rationals& out_rationals) { - LoggerD("Entered"); + ScopeLogger(); if (EXIF_FORMAT_RATIONAL == entry->format && entry->components >= required_count && entry->data) { const ExifByteOrder order = exif_data_get_byte_order(exif_data); unsigned char* ptr = entry->data; @@ -67,7 +67,7 @@ bool GetRationalsFromEntry(ExifEntry* entry, ExifData* exif_data, unsigned long bool GetGCSPositionFromEntry(ExifEntry* entry, ExifData* exif_data, GCSPosition& out_pos) { // RATIONAL - 3 - LoggerD("Entered"); + ScopeLogger(); if (EXIF_FORMAT_RATIONAL == entry->format && entry->components >= 3 && entry->data) { const ExifByteOrder order = exif_data_get_byte_order(exif_data); out_pos.degrees = Rational(exif_get_rational(entry->data, order)); @@ -81,7 +81,7 @@ bool GetGCSPositionFromEntry(ExifEntry* entry, ExifData* exif_data, GCSPosition& } bool DecomposeExifUndefined(ExifEntry* entry, std::string& type, std::string& value) { - LoggerD("Entered"); + ScopeLogger(); if (!entry || !entry->data) { LoggerW("exif entry is NULL/empty"); return false; @@ -101,7 +101,7 @@ bool DecomposeExifUndefined(ExifEntry* entry, std::string& type, std::string& va PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, ExifData* exif_data, JsonObject* result_obj) { - LoggerD("Entered"); + ScopeLogger(); char buf[2000]; exif_entry_get_value(entry, buf, sizeof(buf)); ExifUtil::printExifEntryInfo(entry, exif_data); @@ -444,7 +444,7 @@ PlatformResult GetExifInfo::ProcessEntry(ExifEntry* entry, ExifData* exif_data, } void GetExifInfo::ContentForeachFunctionProxy(ExifEntry* entry, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); ExifDataHolder* holder = static_cast(user_data); if (!holder) { LoggerE("holder is NULL"); @@ -465,11 +465,12 @@ void GetExifInfo::ContentForeachFunctionProxy(ExifEntry* entry, void* user_data) } void GetExifInfo::DataForeachFunction(ExifContent* content, void* user_data) { + ScopeLogger(); exif_content_foreach_entry(content, ContentForeachFunctionProxy, user_data); } PlatformResult GetExifInfo::LoadFromURI(const std::string& uri, JsonValue* result) { - LoggerD("Entered"); + ScopeLogger(); const std::string& file_path = ExifUtil::convertUriToPath(uri); ExifData* ed = exif_data_new_from_file(file_path.c_str()); if (!ed) { diff --git a/src/exif/jpeg_file.cc b/src/exif/jpeg_file.cc index b46ed6e..e0640e1 100644 --- a/src/exif/jpeg_file.cc +++ b/src/exif/jpeg_file.cc @@ -80,9 +80,11 @@ JpegFile::JpegFile() m_padding_data_size(0), m_in_file(NULL), m_out_file(NULL) { + ScopeLogger(); } JpegFile::~JpegFile() { + ScopeLogger(); delete[] m_in_data; m_in_data = NULL; m_in_data_size = 0; @@ -118,7 +120,7 @@ JpegFile::~JpegFile() { } PlatformResult JpegFile::loadFile(const std::string& path, JpegFilePtr* jpg_ptr) { - LoggerD("Entered"); + ScopeLogger(); JpegFile* new_jpg = new (std::nothrow) JpegFile(); if (!new_jpg) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Memory allocation failed", @@ -136,7 +138,7 @@ PlatformResult JpegFile::loadFile(const std::string& path, JpegFilePtr* jpg_ptr) } PlatformResult JpegFile::load(const std::string& path) { - LoggerD("Entered file: %s", path.c_str()); + ScopeLogger("file: %s", path.c_str()); m_source_file_path = path; @@ -187,7 +189,7 @@ PlatformResult JpegFile::load(const std::string& path) { std::string JpegFile::getPartOfFile(const std::size_t offset, const std::size_t num_bytes_before, const std::size_t num_bytes_after) { - LoggerD("Entered"); + ScopeLogger(); auto start = offset - num_bytes_before; if (offset < num_bytes_before) { start = 0; @@ -207,7 +209,7 @@ std::string JpegFile::getPartOfFile(const std::size_t offset, const std::size_t } common::PlatformResult JpegFile::generateListOfSections() { - LoggerD("Entered"); + ScopeLogger(); // JPEG starts with: // FFD8 (2 bytes) - SOI Marker @@ -407,7 +409,7 @@ common::PlatformResult JpegFile::generateListOfSections() { bool JpegFile::searchForTagInBuffer(const unsigned char* buffer_start, const unsigned char* buffer_end, const JpegMarker marker, std::size_t& out_index) { - LoggerD("Entered start:%p end:%p marker:0x%x", buffer_start, buffer_end, marker); + ScopeLogger("start:%p end:%p marker:0x%x", buffer_start, buffer_end, marker); if (!buffer_start) { LoggerE("buffer_start is NULL"); @@ -441,7 +443,7 @@ bool JpegFile::searchForTagInBuffer(const unsigned char* buffer_start, } PlatformResult JpegFile::setNewExifData(ExifData* new_exif_data) { - LoggerD("Entered"); + ScopeLogger(); AssertMsg(new_exif_data, "Trying to set NULL exif_data!"); JpegFileSectionPtr exif = getExifSection(); @@ -496,7 +498,7 @@ PlatformResult JpegFile::setNewExifData(ExifData* new_exif_data) { } ExifData* JpegFile::getExifData() { - LoggerD("Entered"); + ScopeLogger(); JpegFileSectionPtr exif = getExifSection(); if (!exif) { return NULL; @@ -507,7 +509,7 @@ ExifData* JpegFile::getExifData() { } PlatformResult JpegFile::saveToFile(const std::string& out_path) { - LoggerD("Entered out_path:%s", out_path.c_str()); + ScopeLogger("out_path:%s", out_path.c_str()); PlatformResult status = saveToFilePriv(out_path); if (status) return status; @@ -550,7 +552,7 @@ PlatformResult JpegFile::saveToFile(const std::string& out_path) { } PlatformResult JpegFile::saveToFilePriv(const std::string& out_path) { - LoggerD("Entered out_path:%s", out_path.c_str()); + ScopeLogger("out_path:%s", out_path.c_str()); m_out_file = fopen(out_path.c_str(), "wb"); if (!m_out_file) { @@ -691,7 +693,7 @@ PlatformResult JpegFile::saveToFilePriv(const std::string& out_path) { } JpegFileSectionPtr JpegFile::getExifSection() { - LoggerD("Entered"); + ScopeLogger(); std::size_t num_exif_sections = 0; JpegFileSectionPtr first_exif_section; diff --git a/src/exif/rational.cc b/src/exif/rational.cc index 2df6970..fb0e446 100644 --- a/src/exif/rational.cc +++ b/src/exif/rational.cc @@ -31,17 +31,20 @@ const double DOUBLE_ERROR_REPRESENTATION = static_cast(0x7FFFFFFF); } // namespace Rational::Rational() : nominator(0), denominator(0) { + ScopeLogger(); } Rational::Rational(ExifLong nom, ExifLong denom) : nominator(nom), denominator(denom) { + ScopeLogger(); } Rational::Rational(const ExifRational& exif_rational) : nominator(exif_rational.numerator), denominator(exif_rational.denominator) { + ScopeLogger(); } Rational Rational::createFromDouble(const double value, const long precision) { - LoggerD("Entered value:%f precision:%d", value, precision); + ScopeLogger("value:%f precision:%d", value, precision); if (value < 0.0) { LoggerW("Trying to create negative Rational: %f!", value); return Rational(); @@ -149,7 +152,7 @@ double Rational::toDouble() const { } Rational Rational::createFromExposureTimeString(const std::string& exp_time) { - LoggerD("Entered"); + ScopeLogger(); if (exp_time.length() == 0) { return Rational::createInvalid(); // lets assume that empty string means 0, // however exposure time = 0 is @@ -219,7 +222,7 @@ std::string Rational::toString() const { } std::string Rational::toExposureTimeString() const { - LoggerD("Entered"); + ScopeLogger(); if (!isValid() || 0 == nominator) { return std::string(); } diff --git a/src/feedback/feedback_instance.cc b/src/feedback/feedback_instance.cc index fe5719b..ac06ef5 100644 --- a/src/feedback/feedback_instance.cc +++ b/src/feedback/feedback_instance.cc @@ -45,7 +45,7 @@ const std::string kPrivilegeHaptic = "http://tizen.org/privilege/haptic"; FeedbackInstance::FeedbackInstance() : m_feedbackMapsPtr(new FeedbackMaps), m_feedbackManagerPtr(new FeedbackManager(this->m_feedbackMapsPtr)) { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; #define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&FeedbackInstance::x, this, _1, _2)); @@ -56,11 +56,11 @@ FeedbackInstance::FeedbackInstance() } FeedbackInstance::~FeedbackInstance() { - LoggerD("Enter"); + ScopeLogger(); } void FeedbackInstance::IsPatternSupported(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); const auto pattern = args.get("pattern").get(); const auto type = args.get("type").get(); @@ -75,7 +75,7 @@ void FeedbackInstance::IsPatternSupported(const picojson::value& args, picojson: } void FeedbackInstance::Play(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeHaptic, &out); @@ -91,7 +91,7 @@ void FeedbackInstance::Play(const picojson::value& args, picojson::object& out) } void FeedbackInstance::Stop(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeHaptic, &out); diff --git a/src/feedback/feedback_manager.cc b/src/feedback/feedback_manager.cc index cc5da3d..3aba534 100644 --- a/src/feedback/feedback_manager.cc +++ b/src/feedback/feedback_manager.cc @@ -73,9 +73,12 @@ FeedbackMaps::FeedbackMaps() {"BT_DISCONNECTED", FEEDBACK_PATTERN_BT_DISCONNECTED}, {"LIST_REORDER", FEEDBACK_PATTERN_LIST_REORDER}, {"LIST_SLIDER", FEEDBACK_PATTERN_LIST_SLIDER}, - {"VOLUME_KEY", FEEDBACK_PATTERN_VOLUME_KEY}} {}; + {"VOLUME_KEY", FEEDBACK_PATTERN_VOLUME_KEY}} { + ScopeLogger(); +}; FeedbackMaps::~FeedbackMaps() { + ScopeLogger(); } feedback_pattern_e const &FeedbackMaps::getPatternFromMap(const std::string &pattern) { @@ -102,7 +105,7 @@ void FeedbackMaps::setPatternSupport(const feedback_pattern_e pattern, const fee } FeedbackManager::FeedbackManager(std::shared_ptr maps) : m_feedbackMapsPtr(maps) { - LoggerD("Entered"); + ScopeLogger(); // feedback API initialization int ret = feedback_initialize(); if (ret != FEEDBACK_ERROR_NONE) { @@ -111,7 +114,7 @@ FeedbackManager::FeedbackManager(std::shared_ptr maps) : m_feedbac } FeedbackManager::~FeedbackManager() { - LoggerD("Entered"); + ScopeLogger(); // feedback library deinitialization int ret = feedback_deinitialize(); @@ -123,7 +126,7 @@ FeedbackManager::~FeedbackManager() { common::PlatformResult FeedbackManager::isPatternSupported(const std::string &pattern, const std::string &type, bool *patternStatus) { - LoggerD("Entered"); + ScopeLogger(); auto &pattern_e = m_feedbackMapsPtr->getPatternFromMap(pattern); auto &type_e = m_feedbackMapsPtr->getTypeFromMap(type); @@ -145,7 +148,7 @@ common::PlatformResult FeedbackManager::isPatternSupported(const std::string &pa } common::PlatformResult FeedbackManager::play(const std::string &pattern, const std::string &type) { - LoggerD("Entered"); + ScopeLogger(); int ret = 0; if (type == "any") { ret = feedback_play(m_feedbackMapsPtr->getPatternFromMap(pattern)); @@ -174,7 +177,7 @@ common::PlatformResult FeedbackManager::play(const std::string &pattern, const s } common::PlatformResult FeedbackManager::stop() { - LoggerD("Entered"); + ScopeLogger(); int ret = feedback_stop(); if (ret != FEEDBACK_ERROR_NONE && ret != FEEDBACK_ERROR_NOT_SUPPORTED) { @@ -186,7 +189,7 @@ common::PlatformResult FeedbackManager::stop() { } PlatformResult FeedbackManager::CodeToResult(const int errorCode, const std::string &message) { - LoggerD("Entered"); + ScopeLogger(); switch (errorCode) { case FEEDBACK_ERROR_NOT_SUPPORTED: @@ -200,7 +203,7 @@ PlatformResult FeedbackManager::CodeToResult(const int errorCode, const std::str } const std::string FeedbackManager::getFeedbackErrorMessage(const int error_code) { - LoggerD("Error code : %d", error_code); + ScopeLogger("Error code : %d", error_code); switch (error_code) { case FEEDBACK_ERROR_OPERATION_FAILED: diff --git a/src/filesystem/filesystem_file.cc b/src/filesystem/filesystem_file.cc index bc0734c..904b609 100644 --- a/src/filesystem/filesystem_file.cc +++ b/src/filesystem/filesystem_file.cc @@ -76,7 +76,7 @@ bool validateCharacter(char c) { */ bool FilesystemBuffer::DecodeData(const std::string& data) { - LoggerD("Enter"); + ScopeLogger(); if (data.length() % 4) { LoggerE("Buffer has invalid length"); return false; @@ -132,7 +132,7 @@ bool FilesystemBuffer::DecodeData(const std::string& data) { } std::string FilesystemBuffer::EncodeData() const { - LoggerD("Enter"); + ScopeLogger(); std::string out; for (size_t i = 0; i < size(); i += 3) { @@ -159,10 +159,11 @@ std::string FilesystemBuffer::EncodeData() const { } FilesystemFile::FilesystemFile(const std::string& path_) : path(path_) { + ScopeLogger(); } bool FilesystemFile::Read(FilesystemBuffer* data, size_t offset, size_t length) { - LoggerD("Enter"); + ScopeLogger(); if (!data) { LoggerE("Missing output buffer"); return false; @@ -215,7 +216,7 @@ bool FilesystemFile::Read(FilesystemBuffer* data, size_t offset, size_t length) } bool FilesystemFile::Write(const FilesystemBuffer& data, size_t offset, bool rewrite) { - LoggerD("Enter"); + ScopeLogger(); FILE* file = nullptr; if (rewrite) { diff --git a/src/filesystem/filesystem_instance.cc b/src/filesystem/filesystem_instance.cc index 3c94825..7a6e3f0 100644 --- a/src/filesystem/filesystem_instance.cc +++ b/src/filesystem/filesystem_instance.cc @@ -38,7 +38,7 @@ using namespace common; using namespace extension::filesystem; FilesystemInstance::FilesystemInstance() { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -71,7 +71,7 @@ FilesystemInstance::FilesystemInstance() { } FilesystemInstance::~FilesystemInstance() { - LoggerD("enter"); + ScopeLogger(); FilesystemManager::GetInstance().StopListening(); FilesystemManager::GetInstance().RemoveListener(); } @@ -83,19 +83,19 @@ FilesystemInstance::~FilesystemInstance() { } void FilesystemInstance::FileCreateSync(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "location", out) const std::string& location = args.get("location").get(); auto onSuccess = [&](const FilesystemStat& data) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); ReportSuccess(data.toJSON(), out); }; auto onError = [&](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); PrepareError(e, out); }; @@ -103,7 +103,7 @@ void FilesystemInstance::FileCreateSync(const picojson::value& args, picojson::o } void FilesystemInstance::FileRename(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "oldPath", out) @@ -114,7 +114,7 @@ void FilesystemInstance::FileRename(const picojson::value& args, picojson::objec const std::string& newPath = args.get("newPath").get(); auto onSuccess = [this, callback_id](const FilesystemStat& data) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -123,7 +123,7 @@ void FilesystemInstance::FileRename(const picojson::value& args, picojson::objec }; auto onError = [this, callback_id](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -137,7 +137,7 @@ void FilesystemInstance::FileRename(const picojson::value& args, picojson::objec } void FilesystemInstance::FileRead(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "location", out) CHECK_EXIST(args, "offset", out) @@ -149,7 +149,7 @@ void FilesystemInstance::FileRead(const picojson::value& args, picojson::object& size_t length = static_cast(args.get("length").get()); auto onSuccess = [this, callback_id](const std::string& data) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -158,7 +158,7 @@ void FilesystemInstance::FileRead(const picojson::value& args, picojson::object& }; auto onError = [this, callback_id](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -172,7 +172,7 @@ void FilesystemInstance::FileRead(const picojson::value& args, picojson::object& } void FilesystemInstance::FileReadSync(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); CHECK_EXIST(args, "location", out) CHECK_EXIST(args, "offset", out) @@ -183,12 +183,12 @@ void FilesystemInstance::FileReadSync(const picojson::value& args, picojson::obj size_t length = static_cast(args.get("length").get()); auto onSuccess = [this, &out](const std::string& data) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); ReportSuccess(picojson::value(data), out); }; auto onError = [this, &out](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); PrepareError(e, out); }; @@ -196,7 +196,7 @@ void FilesystemInstance::FileReadSync(const picojson::value& args, picojson::obj } void FilesystemInstance::FileWrite(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "location", out) CHECK_EXIST(args, "data", out) @@ -210,7 +210,7 @@ void FilesystemInstance::FileWrite(const picojson::value& args, picojson::object bool rewrite = static_cast(args.get("rewrite").get()); auto onSuccess = [this, callback_id]() { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -219,7 +219,7 @@ void FilesystemInstance::FileWrite(const picojson::value& args, picojson::object }; auto onError = [this, callback_id](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -233,7 +233,7 @@ void FilesystemInstance::FileWrite(const picojson::value& args, picojson::object } void FilesystemInstance::FileWriteSync(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "location", out) CHECK_EXIST(args, "data", out) @@ -246,12 +246,12 @@ void FilesystemInstance::FileWriteSync(const picojson::value& args, picojson::ob bool rewrite = static_cast(args.get("rewrite").get()); auto onSuccess = [this, &out]() { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); ReportSuccess(out); }; auto onError = [this, &out](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); PrepareError(e, out); }; @@ -259,7 +259,7 @@ void FilesystemInstance::FileWriteSync(const picojson::value& args, picojson::ob } void FilesystemInstance::FileStat(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "location", out) @@ -268,7 +268,7 @@ void FilesystemInstance::FileStat(const picojson::value& args, picojson::object& const std::string& location = args.get("location").get(); auto onSuccess = [this, callback_id](const FilesystemStat& data) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -277,7 +277,7 @@ void FilesystemInstance::FileStat(const picojson::value& args, picojson::object& }; auto onError = [this, callback_id](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -291,19 +291,19 @@ void FilesystemInstance::FileStat(const picojson::value& args, picojson::object& } void FilesystemInstance::FileStatSync(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); CHECK_EXIST(args, "location", out) const std::string& location = args.get("location").get(); auto onSuccess = [&](const FilesystemStat& data) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); ReportSuccess(data.toJSON(), out); }; auto onError = [&](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); PrepareError(e, out); }; @@ -312,10 +312,10 @@ void FilesystemInstance::FileStatSync(const picojson::value& args, picojson::obj void FilesystemInstance::FilesystemFetchVirtualRoots(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); auto onSuccess = [&](const std::vector& result) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); picojson::array roots; for (const auto& root : result) { roots.push_back(root.ToJson()); @@ -324,7 +324,7 @@ void FilesystemInstance::FilesystemFetchVirtualRoots(const picojson::value& args }; auto onError = [&](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); PrepareError(e, out); }; @@ -333,10 +333,10 @@ void FilesystemInstance::FilesystemFetchVirtualRoots(const picojson::value& args void FilesystemInstance::FileSystemManagerFetchStorages(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); auto onSuccess = [&](const common::Storages& result) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); picojson::array storages; storages.reserve(result.size()); for (const auto storage : result) { @@ -346,28 +346,28 @@ void FilesystemInstance::FileSystemManagerFetchStorages(const picojson::value& a }; auto onError = [&](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); PrepareError(e, out); }; FilesystemManager::GetInstance().FetchStorages(onSuccess, onError); } void FilesystemInstance::StartListening(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); FilesystemManager::GetInstance().StartListening(); ReportSuccess(out); } void FilesystemInstance::StopListening(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); FilesystemManager::GetInstance().StopListening(); ReportSuccess(out); } void FilesystemInstance::onFilesystemStateChangeSuccessCallback(const common::Storage& storage) { - LoggerD("entered"); + ScopeLogger(); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); @@ -379,7 +379,7 @@ void FilesystemInstance::onFilesystemStateChangeSuccessCallback(const common::St } void FilesystemInstance::onFilesystemStateChangeErrorCallback() { - LoggerD("enter"); + ScopeLogger(); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); LogAndReportError(UnknownException(std::string("Failed to registerd listener")), obj); @@ -390,7 +390,7 @@ void FilesystemInstance::onFilesystemStateChangeErrorCallback() { void FilesystemInstance::FileSystemManagerMakeDirectory(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "location", out) @@ -398,7 +398,7 @@ void FilesystemInstance::FileSystemManagerMakeDirectory(const picojson::value& a const std::string& location = args.get("location").get(); auto onResult = [this, callback_id](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onResult"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -410,6 +410,7 @@ void FilesystemInstance::FileSystemManagerMakeDirectory(const picojson::value& a }; auto onAction = [location, onResult]() { + ScopeLogger("Entered into asynchronous function, onAction"); FilesystemManager::GetInstance().MakeDirectory(location, onResult); }; @@ -418,14 +419,14 @@ void FilesystemInstance::FileSystemManagerMakeDirectory(const picojson::value& a void FilesystemInstance::FileSystemManagerMakeDirectorySync(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "location", out) const std::string& location = args.get("location").get(); auto onResult = [&](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onResult"); if (e == FilesystemError::DirectoryExists) ReportSuccess(out); else @@ -436,7 +437,7 @@ void FilesystemInstance::FileSystemManagerMakeDirectorySync(const picojson::valu } void FilesystemInstance::ReadDir(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemRead, &out); CHECK_EXIST(args, "pathToDir", out) CHECK_EXIST(args, "callbackId", out) @@ -445,7 +446,7 @@ void FilesystemInstance::ReadDir(const picojson::value& args, picojson::object& const std::string& pathToDir = args.get("pathToDir").get(); auto onSuccess = [this, callback_id](const std::vector& paths) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); picojson::value result = picojson::value(picojson::array()); ; picojson::array& statPaths = result.get(); @@ -461,7 +462,7 @@ void FilesystemInstance::ReadDir(const picojson::value& args, picojson::object& }; auto onError = [this, callback_id](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -475,7 +476,7 @@ void FilesystemInstance::ReadDir(const picojson::value& args, picojson::object& } void FilesystemInstance::UnlinkFile(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "pathToFile", out) @@ -483,7 +484,7 @@ void FilesystemInstance::UnlinkFile(const picojson::value& args, picojson::objec const std::string& pathToFile = args.get("pathToFile").get(); auto onSuccess = [this, callback_id]() { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); picojson::value result = picojson::value(); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); @@ -493,7 +494,7 @@ void FilesystemInstance::UnlinkFile(const picojson::value& args, picojson::objec }; auto onError = [this, callback_id](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -507,7 +508,7 @@ void FilesystemInstance::UnlinkFile(const picojson::value& args, picojson::objec } void FilesystemInstance::RemoveDirectory(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "pathToDelete", out) @@ -515,7 +516,7 @@ void FilesystemInstance::RemoveDirectory(const picojson::value& args, picojson:: const std::string& pathToDelete = args.get("pathToDelete").get(); auto onSuccess = [this, callback_id]() { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); picojson::value result = picojson::value(); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); @@ -525,7 +526,7 @@ void FilesystemInstance::RemoveDirectory(const picojson::value& args, picojson:: }; auto onError = [this, callback_id](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -539,7 +540,7 @@ void FilesystemInstance::RemoveDirectory(const picojson::value& args, picojson:: } void FilesystemInstance::CopyTo(const picojson::value& args, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeFilesystemWrite, &out); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "originFilePath", out) @@ -552,7 +553,7 @@ void FilesystemInstance::CopyTo(const picojson::value& args, picojson::object& o const bool& overwrite = args.get("overwrite").get(); auto onSuccess = [this, callback_id]() { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); picojson::value result = picojson::value(); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); @@ -562,7 +563,7 @@ void FilesystemInstance::CopyTo(const picojson::value& args, picojson::object& o }; auto onError = [this, callback_id](FilesystemError e) { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, onError"); picojson::value response = picojson::value(picojson::object()); picojson::object& obj = response.get(); obj["callbackId"] = picojson::value(callback_id); @@ -576,7 +577,7 @@ void FilesystemInstance::CopyTo(const picojson::value& args, picojson::object& o } void FilesystemInstance::PrepareError(const FilesystemError& error, picojson::object& out) { - LoggerD("enter"); + ScopeLogger(); switch (error) { case FilesystemError::None: LogAndReportError(UnknownException("PLATFORM ERROR"), out); @@ -616,19 +617,19 @@ void FilesystemInstance::PrepareError(const FilesystemError& error, picojson::ob void FilesystemInstance::FileSystemManagerGetCanonicalPath(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); // TODO: any privilege needed? CHECK_EXIST(args, "path", out); const std::string& path = args.get("path").get(); auto onSuccess = [&](const std::string& canonicalPath) { - LoggerD("Enter"); + ScopeLogger("Entered into asynchronous function, onSuccess"); ReportSuccess(picojson::value(canonicalPath), out); }; auto onError = [&](FilesystemError e) { - LoggerD("Enter"); + ScopeLogger("Entered into asynchronous function, onError"); PrepareError(e, out); }; diff --git a/src/filesystem/filesystem_manager.cc b/src/filesystem/filesystem_manager.cc index d4c7b7e..7407aa0 100644 --- a/src/filesystem/filesystem_manager.cc +++ b/src/filesystem/filesystem_manager.cc @@ -62,7 +62,7 @@ int unlink_with_base_dir_cb(const char* fpath, const struct stat* sb, int typefl } FilesystemError copyFile(const std::string& originPath, const std::string& destPath) { - LoggerD("enter src %s dst %s", originPath.c_str(), destPath.c_str()); + ScopeLogger("src %s dst %s", originPath.c_str(), destPath.c_str()); std::ifstream src(originPath, std::ios::in | std::ios::binary); std::ofstream dst(destPath, std::ios::out | std::ios::binary); @@ -80,7 +80,7 @@ FilesystemError copyFile(const std::string& originPath, const std::string& destP } FilesystemError copyDirectory(const std::string& originPath, const std::string& destPath) { - LoggerD("enter src %s dst %s", originPath.c_str(), destPath.c_str()); + ScopeLogger("src %s dst %s", originPath.c_str(), destPath.c_str()); FilesystemStat destStat = FilesystemStat::getStat(destPath); int status; @@ -127,7 +127,7 @@ FilesystemError copyDirectory(const std::string& originPath, const std::string& FilesystemError perform_deep_copy(const std::string& originPath, const std::string& destPath, bool overwrite) { - LoggerD("enter src %s dst %s", originPath.c_str(), destPath.c_str()); + ScopeLogger("rc %s dst %s", originPath.c_str(), destPath.c_str()); FilesystemStat originStat = FilesystemStat::getStat(originPath); FilesystemStat destStat = FilesystemStat::getStat(destPath); int status; @@ -184,7 +184,7 @@ FilesystemError perform_deep_copy(const std::string& originPath, const std::stri } FilesystemError make_directory_worker(const std::string& path) { - LoggerD("enter: %s", path.c_str()); + ScopeLogger("path %s", path.c_str()); auto fsstat = FilesystemStat::getStat(path); if (fsstat.valid) { if (fsstat.isDirectory) { @@ -216,22 +216,22 @@ FilesystemError make_directory_worker(const std::string& path) { void FilesystemManager::FetchStorages( const std::function& success_cb, const std::function& error_cb) { - LoggerD("Entered"); + ScopeLogger(); success_cb(fs_provider_.GetStorages()); } FilesystemManager::FilesystemManager() : listener_(nullptr), fs_provider_(common::FilesystemProvider::Create()) { - LoggerD("enter"); + ScopeLogger(); } FilesystemManager::~FilesystemManager() { - LoggerD("enter"); + ScopeLogger(); } FilesystemManager& FilesystemManager::GetInstance() { - LoggerD("enter"); + ScopeLogger(); static FilesystemManager instance; return instance; } @@ -239,7 +239,7 @@ FilesystemManager& FilesystemManager::GetInstance() { void FilesystemManager::StatPath(const std::string& path, const std::function& success_cb, const std::function& error_cb) { - LoggerD("enter"); + ScopeLogger(); FilesystemStat statData = FilesystemStat::getStat(path); if (!statData.valid) { error_cb(statData.error); @@ -252,14 +252,14 @@ void FilesystemManager::StatPath(const std::string& path, void FilesystemManager::GetVirtualRoots( const std::function& success_cb, const std::function& error_cb) { - LoggerD("enter"); + ScopeLogger(); success_cb(fs_provider_.GetVirtualPaths()); } void FilesystemManager::CreateFile(const std::string& path, const std::function& success_cb, const std::function& error_cb) { - LoggerD("enter"); + ScopeLogger(); const mode_t create_mode = S_IRWXU | S_IRWXG | S_IRWXO; int status; status = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDWR | O_CREAT, create_mode)); @@ -285,14 +285,14 @@ void FilesystemManager::CreateFile(const std::string& path, void FilesystemManager::MakeDirectory(const std::string& path, const std::function& result_cb) { - LoggerD("enter"); + ScopeLogger(); result_cb(make_directory_worker(path)); } void FilesystemManager::Rename(const std::string& oldPath, const std::string& newPath, const std::function& success_cb, const std::function& error_cb) { - LoggerD("enter"); + ScopeLogger(); int status = rename(oldPath.c_str(), newPath.c_str()); if (0 != status) { @@ -345,7 +345,7 @@ void FilesystemManager::Rename(const std::string& oldPath, const std::string& ne void FilesystemManager::ReadDir( const std::string& path, const std::function&)>& success_cb, const std::function& error_cb) { - LoggerD("entered"); + ScopeLogger(); std::vector fileList; DIR* dp = nullptr; @@ -375,7 +375,7 @@ void FilesystemManager::ReadDir( void FilesystemManager::UnlinkFile(const std::string& path, const std::function& success_cb, const std::function& error_cb) { - LoggerD("enter"); + ScopeLogger(); if (unlink(path.c_str()) != 0) { LoggerE("Error occured while deleting file"); error_cb(FilesystemError::Other); @@ -387,7 +387,7 @@ void FilesystemManager::UnlinkFile(const std::string& path, const std::function< void FilesystemManager::RemoveDirectory(const std::string& path, const std::function& success_cb, const std::function& error_cb) { - LoggerD("enter"); + ScopeLogger(); const int maxDirOpened = 64; if (nftw(path.c_str(), unlink_with_base_dir_cb, maxDirOpened, FTW_DEPTH | FTW_PHYS) != 0) { LoggerE("Error occured"); @@ -400,7 +400,7 @@ void FilesystemManager::RemoveDirectory(const std::string& path, void FilesystemManager::FileRead(const std::string& path, size_t offset, size_t length, const std::function& success_cb, const std::function& error_cb) { - LoggerD("enter"); + ScopeLogger(); FilesystemFile file(path); FilesystemBuffer buffer; if (!file.Read(&buffer, offset, length)) { @@ -416,7 +416,7 @@ void FilesystemManager::FileRead(const std::string& path, size_t offset, size_t void FilesystemManager::FileWrite(const std::string& path, const std::string& data, size_t offset, bool rewrite, const std::function& success_cb, const std::function& error_cb) { - LoggerD("enter"); + ScopeLogger(); FilesystemFile file(path); FilesystemBuffer buffer; // Decode buffer data @@ -435,7 +435,7 @@ void FilesystemManager::FileWrite(const std::string& path, const std::string& da } void FilesystemManager::StartListening() { - LoggerD("Entered"); + ScopeLogger(); auto set = std::bind(&FilesystemManager::OnStorageDeviceChanged, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); @@ -443,7 +443,7 @@ void FilesystemManager::StartListening() { } void FilesystemManager::StopListening() { - LoggerD("Entered"); + ScopeLogger(); fs_provider_.UnregisterDeviceChangeState(); } @@ -451,7 +451,7 @@ void FilesystemManager::StopListening() { void FilesystemManager::OnStorageDeviceChanged(common::Storage const& _storage, common::StorageState _old, common::StorageState _new) { - LoggerD("Entered"); + ScopeLogger(); if (listener_) { listener_->onFilesystemStateChangeSuccessCallback(_storage); } @@ -461,7 +461,7 @@ void FilesystemManager::CopyTo(const std::string& originFilePath, const std::string& destinationFilePath, const bool overwrite, const std::function& success_cb, const std::function& error_cb) { - LoggerD("enter"); + ScopeLogger(); FilesystemError retval = perform_deep_copy(originFilePath, destinationFilePath, overwrite); if (FilesystemError::None == retval) { success_cb(); @@ -472,19 +472,19 @@ void FilesystemManager::CopyTo(const std::string& originFilePath, } void FilesystemManager::AddListener(FilesystemStateChangeListener* listener) { - LoggerD("enter"); + ScopeLogger(); listener_ = listener; } void FilesystemManager::RemoveListener() { - LoggerD("enter"); + ScopeLogger(); listener_ = NULL; } void FilesystemManager::GetCanonicalPath(const std::string& path, const std::function& success_cb, const std::function& error_cb) { - LoggerD("Enter"); + ScopeLogger(); char* canonicalPath = nullptr; SCOPE_EXIT { diff --git a/src/filesystem/filesystem_stat.cc b/src/filesystem/filesystem_stat.cc index 889a808..84646a8 100644 --- a/src/filesystem/filesystem_stat.cc +++ b/src/filesystem/filesystem_stat.cc @@ -39,10 +39,11 @@ FilesystemStat::FilesystemStat() mtime(0), size(0), nlink(0) { + ScopeLogger(); } picojson::value FilesystemStat::toJSON() const { - LoggerD("Enter"); + ScopeLogger(); picojson::value retval = picojson::value(picojson::object()); picojson::object& obj = retval.get(); @@ -59,12 +60,10 @@ picojson::value FilesystemStat::toJSON() const { } FilesystemStat FilesystemStat::getStat(const std::string& path) { - LoggerD("Enter"); + ScopeLogger(); struct stat aStatObj; FilesystemStat _result; - LoggerD("enter"); - if (0 != stat(path.c_str(), &aStatObj)) { if (ENOENT == errno) { LoggerI("File/directory: %s not found", path.c_str()); diff --git a/src/filesystem/filesystem_utils.cc b/src/filesystem/filesystem_utils.cc old mode 100755 new mode 100644 index c437b31..c6d04e5 --- a/src/filesystem/filesystem_utils.cc +++ b/src/filesystem/filesystem_utils.cc @@ -21,7 +21,7 @@ namespace FilesystemUtils { std::string get_storage_dir_path(int id, storage_directory_e typeToCheck) { - LoggerD("Enter"); + ScopeLogger(); char* platformPath = NULL; int result = storage_get_directory(id, typeToCheck, &platformPath); if (STORAGE_ERROR_NONE != result) { @@ -35,6 +35,7 @@ std::string get_storage_dir_path(int id, storage_directory_e typeToCheck) { } std::string get_dirname(const std::string& path) { + ScopeLogger(); char* dir = g_path_get_dirname(path.c_str()); if (dir) { std::string dir_result(dir); @@ -46,6 +47,7 @@ std::string get_dirname(const std::string& path) { } std::string get_basename(const std::string& path) { + ScopeLogger(); // basename will modify content: pass a copy std::string buf = path.c_str(); return std::string(basename(const_cast(buf.c_str()))); diff --git a/src/humanactivitymonitor/humanactivitymonitor_instance.cc b/src/humanactivitymonitor/humanactivitymonitor_instance.cc index efa07ab..8deedb4 100644 --- a/src/humanactivitymonitor/humanactivitymonitor_instance.cc +++ b/src/humanactivitymonitor/humanactivitymonitor_instance.cc @@ -44,7 +44,7 @@ using common::ErrorCode; using common::TaskQueue; HumanActivityMonitorInstance::HumanActivityMonitorInstance() { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -68,11 +68,11 @@ HumanActivityMonitorInstance::HumanActivityMonitorInstance() { } HumanActivityMonitorInstance::~HumanActivityMonitorInstance() { - LoggerD("Enter"); + ScopeLogger(); } PlatformResult HumanActivityMonitorInstance::Init() { - LoggerD("Enter"); + ScopeLogger(); if (!manager_) { manager_ = std::make_shared(); const PlatformResult& result = manager_->Init(); @@ -95,7 +95,7 @@ PlatformResult HumanActivityMonitorInstance::Init() { void HumanActivityMonitorInstance::HumanActivityMonitorManagerGetHumanActivityData( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "type", out) CHECK_PRIVILEGE_ACCESS(kPrivilegeHealthInfo, &out); @@ -115,6 +115,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerGetHumanActivityDa const auto callback_id = args.get("callbackId").get(); auto get = [this, type, callback_id]() -> void { + ScopeLogger("Entered into asynchronous function, get"); picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); response_obj["callbackId"] = picojson::value(callback_id); @@ -138,7 +139,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerGetHumanActivityDa void HumanActivityMonitorInstance::HumanActivityMonitorManagerStart(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "type", out) CHECK_PRIVILEGE_ACCESS(kPrivilegeHealthInfo, &out); @@ -158,6 +159,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerStart(const picojs const auto listener_id = args.get("listenerId").get(); JsonCallback cb = [this, listener_id](picojson::value* data) -> void { + ScopeLogger("Entered into asynchronous function, cb"); if (!data) { LOGGER(ERROR) << "No data passed to json callback"; return; @@ -179,7 +181,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerStart(const picojs void HumanActivityMonitorInstance::HumanActivityMonitorManagerStop(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "type", out) CHECK_PRIVILEGE_ACCESS(kPrivilegeHealthInfo, &out); @@ -206,7 +208,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerStop(const picojso void HumanActivityMonitorInstance::HumanActivityMonitorManagerAddActivityRecognitionListener( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeHealthInfo, &out); CHECK_EXIST(args, "type", out) @@ -221,6 +223,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerAddActivityRecogni const auto& listener_id = args.get("listenerId").get(); JsonCallback cb = [this, listener_id](picojson::value* data) -> void { + ScopeLogger("Entered into asynchronous function, cb"); if (!data) { LOGGER(ERROR) << "No data passed to json callback"; return; @@ -245,7 +248,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerAddActivityRecogni void HumanActivityMonitorInstance::HumanActivityMonitorManagerRemoveActivityRecognitionListener( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeHealthInfo, &out); CHECK_EXIST(args, "watchId", out) @@ -267,7 +270,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerRemoveActivityReco void HumanActivityMonitorInstance::HumanActivityMonitorManagerStartRecorder( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeHealthInfo, &out); CHECK_EXIST(args, "type", out) @@ -309,7 +312,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerStartRecorder( void HumanActivityMonitorInstance::HumanActivityMonitorManagerStopRecorder( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "type", out) const auto& type = args.get("type").get(); @@ -330,7 +333,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerStopRecorder( void HumanActivityMonitorInstance::HumanActivityMonitorManagerReadRecorderData( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeHealthInfo, &out); CHECK_EXIST(args, "type", out) CHECK_EXIST(args, "query", out) @@ -353,6 +356,7 @@ void HumanActivityMonitorInstance::HumanActivityMonitorManagerReadRecorderData( const auto callback_id = args.get("callbackId").get(); auto get = [this, type, query, callback_id]() -> void { + ScopeLogger("Entered into asynchronous function, get"); picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); response_obj["callbackId"] = picojson::value(callback_id); diff --git a/src/humanactivitymonitor/humanactivitymonitor_manager.cc b/src/humanactivitymonitor/humanactivitymonitor_manager.cc index a741783..269f308 100644 --- a/src/humanactivitymonitor/humanactivitymonitor_manager.cc +++ b/src/humanactivitymonitor/humanactivitymonitor_manager.cc @@ -152,7 +152,7 @@ struct PedometerDataWrapper : public sensor_pedometer_data_t { }; static int64_t getCurrentTimeStamp(unsigned long long evTime) { - LoggerD("Enter"); + ScopeLogger(); struct timespec t; unsigned long long systemCurrentTime = 0; unsigned long long realCurrentTime = 0; @@ -283,7 +283,6 @@ class HumanActivityMonitorManager::Monitor { } JsonCallback& event_callback() { - ScopeLogger(type()); return event_callback_; } @@ -1296,7 +1295,7 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() ScopeLogger(); auto convert_pedometer = [](sensor_event_s* event, picojson::object* data) -> PlatformResult { - ScopeLogger("convert_pedometer"); + ScopeLogger("Entered into asynchronous function, convert_pedometer"); const auto pedometer_data = (PedometerDataWrapper*)event; @@ -1356,7 +1355,7 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() }; auto convert_hrm = [](sensor_event_s* event, picojson::object* data) -> PlatformResult { - ScopeLogger("convert_hrm"); + ScopeLogger("Entered into asynchronous function, convert_hrm"); LOGGER(DEBUG) << "Sensor event:"; LOGGER(DEBUG) << " |- accuracy: " << event->accuracy; @@ -1384,7 +1383,7 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() }; auto convert_sleep = [](sensor_event_s* event, picojson::object* data) -> PlatformResult { - ScopeLogger("convert_sleep"); + ScopeLogger("Entered into asynchronous function, convert_sleep"); if (event->value_count < 1) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "To few values of SLEEP event"); @@ -1419,7 +1418,7 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() }; auto convert_recorded_pedometer = [](void* data, picojson::object* obj) -> PlatformResult { - ScopeLogger("convert_recorded_pedometer"); + ScopeLogger("Entered into asynchronous function, convert_recorded_pedometer"); SensorRecorderDataMap map_int{{SENSOR_RECORDER_DATA_STEPS, kRecordedTotalStepCount}, {SENSOR_RECORDER_DATA_WALK_STEPS, kRecordedWalkStepCount}, @@ -1442,7 +1441,7 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() }; auto convert_recorded_hrm = [](void* data, picojson::object* obj) -> PlatformResult { - ScopeLogger("convert_recorded_hrm"); + ScopeLogger("Entered into asynchronous function, convert_recorded_hrm"); SensorRecorderDataMap map_int{ {SENSOR_RECORDER_DATA_HEART_RATE, kRecordedHeartRate}, @@ -1457,7 +1456,7 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() }; auto convert_recorded_sleep_monitor = [](void* data, picojson::object* obj) -> PlatformResult { - ScopeLogger("convert_recorded_sleep_monitor"); + ScopeLogger("Entered into asynchronous function, convert_recorded_sleep_monitor"); SensorRecorderDataMap map_int{{SENSOR_RECORDER_DATA_SLEEP_STATE, kStatus}}; @@ -1470,7 +1469,7 @@ HumanActivityMonitorManager::HumanActivityMonitorManager() }; auto convert_recorded_pressure = [](void* data, picojson::object* obj) -> PlatformResult { - ScopeLogger("convert_recorded_pressure"); + ScopeLogger("Entered into asynchronous function, convert_recorded_pressure"); SensorRecorderDataMap map_double{{SENSOR_RECORDER_DATA_MAX_PRESSURE, kRecordedMax}, {SENSOR_RECORDER_DATA_MIN_PRESSURE, kRecordedMin}, diff --git a/src/inputdevice/inputdevice_instance.cc b/src/inputdevice/inputdevice_instance.cc index 91d3084..9ec8fd0 100644 --- a/src/inputdevice/inputdevice_instance.cc +++ b/src/inputdevice/inputdevice_instance.cc @@ -21,11 +21,11 @@ namespace extension { namespace inputdevice { InputDeviceInstance::InputDeviceInstance() { - LoggerD("Enter"); + ScopeLogger(); } InputDeviceInstance::~InputDeviceInstance() { - LoggerD("Enter"); + ScopeLogger(); } } // namespace inputdevice diff --git a/src/iotcon/iotcon_instance.cc b/src/iotcon/iotcon_instance.cc index 4996f1e..c71deeb 100644 --- a/src/iotcon/iotcon_instance.cc +++ b/src/iotcon/iotcon_instance.cc @@ -64,12 +64,12 @@ class CallbackDataManager { bool IfExists(CallbackData* data); private: - CallbackDataManager() {}; - CallbackDataManager(const CallbackDataManager &) = delete; - CallbackDataManager(const CallbackDataManager &&) = delete; - CallbackDataManager& operator=(const CallbackDataManager &) = delete; - CallbackDataManager& operator=(const CallbackDataManager &&) = delete; - ~CallbackDataManager() {}; + CallbackDataManager(){}; + CallbackDataManager(const CallbackDataManager&) = delete; + CallbackDataManager(const CallbackDataManager&&) = delete; + CallbackDataManager& operator=(const CallbackDataManager&) = delete; + CallbackDataManager& operator=(const CallbackDataManager&&) = delete; + ~CallbackDataManager(){}; std::vector callback_; std::mutex callback_mtx_; }; @@ -484,6 +484,7 @@ common::TizenResult IotconInstance::ResourceSetRequestListener(const picojson::o if (!resource->request_listener) { resource->request_listener = [this, id](const common::TizenResult&, const picojson::value& v) { + ScopeLogger("Entered into asynchronous function, resource->request_listener"); picojson::value request{picojson::object{}}; auto& obj = request.get(); @@ -983,6 +984,7 @@ common::TizenResult IotconInstance::RemoteResourceStartObserving(const picojson: IotconUtils::ToObservePolicy(args.find(kObservePolicy)->second.get().c_str()); ptr->observe_listener = [this, ptr](const common::TizenResult& res, const picojson::value& v) { + ScopeLogger("Entered into asynchronous function, ptr->observe_listener"); picojson::value response{picojson::object{}}; auto& obj = response.get(); @@ -1109,6 +1111,7 @@ common::TizenResult IotconInstance::RemoteResourceStartCaching(const picojson::o ptr->cache_change_listener = [this, ptr](const common::TizenResult& res, const picojson::value& v) { + ScopeLogger("Entered into asynchronous function, ptr->cache_change_listener"); picojson::value response{picojson::object{}}; auto& obj = response.get(); @@ -1188,6 +1191,7 @@ common::TizenResult IotconInstance::RemoteResourceSetResourceStateChangeListener } ptr->state_listener = [this, ptr](const common::TizenResult& res, const picojson::value& v) { + ScopeLogger("Entered into asynchronous function, ptr->state_listener"); picojson::value response{picojson::object{}}; auto& obj = response.get(); @@ -1352,6 +1356,7 @@ common::TizenResult IotconInstance::ClientFindResource(const picojson::object& a long long id = GetId(args); auto response = [this, id](const common::TizenResult& res, const picojson::value& v) { + ScopeLogger("Entered into asynchronous function, response"); picojson::value response{picojson::object{}}; auto& obj = response.get(); @@ -1417,6 +1422,7 @@ common::TizenResult IotconInstance::ClientAddPresenceEventListener(const picojso long long id = presence->id; presence->presence_listener = [this, id](const common::TizenResult&, const picojson::value& v) { + ScopeLogger("Entered into asynchronous function, presence->presence_listener"); picojson::value response{picojson::object{}}; auto& obj = response.get(); @@ -1514,6 +1520,7 @@ common::TizenResult IotconInstance::ClientFindDeviceInfo(const picojson::object& long long id = GetId(args); auto response = [this, id](const common::TizenResult& res, const picojson::value& v) { + ScopeLogger("Entered into asynchronous function, response"); picojson::value response{picojson::object{}}; auto& obj = response.get(); @@ -1611,6 +1618,7 @@ common::TizenResult IotconInstance::ClientFindPlatformInfo(const picojson::objec long long id = GetId(args); auto response = [this, id](const common::TizenResult& res, const picojson::value& v) { + ScopeLogger("Entered into asynchronous function, response"); picojson::value response{picojson::object{}}; auto& obj = response.get(); @@ -1814,6 +1822,7 @@ common::TizenResult IotconInstance::AddGeneratedPinListener(const picojson::obje ScopeLogger(); auto listener = [this](const char* pin, long watchId) { + ScopeLogger("Entered into asynchronous function, listener"); picojson::object obj; obj[kId] = picojson::value{(double)watchId}; obj["pin"] = picojson::value{pin}; @@ -1837,6 +1846,7 @@ common::PostCallback IotconInstance::PostForMethodCall(const common::AsyncToken& ScopeLogger(); return [this, token, resource](const common::TizenResult& result, const picojson::value& v) { + ScopeLogger("Entered into asynchronous function, returned value"); auto value = IotconClientManager::GetInstance().RemoveRemoteResource(resource); auto& obj = value.get(); diff --git a/src/iotcon/iotcon_manager.cc b/src/iotcon/iotcon_manager.cc index 037b9b6..6db23ed 100644 --- a/src/iotcon/iotcon_manager.cc +++ b/src/iotcon/iotcon_manager.cc @@ -26,9 +26,11 @@ namespace extension { namespace iotcon { IotconManager::IotconManager() : nextWatchId(1) { + ScopeLogger(); } IotconManager& IotconManager::GetInstance() { + ScopeLogger(); static IotconManager instance; return instance; } diff --git a/src/iotcon/iotcon_server_manager.cc b/src/iotcon/iotcon_server_manager.cc index 84c78ad..40883f4 100644 --- a/src/iotcon/iotcon_server_manager.cc +++ b/src/iotcon/iotcon_server_manager.cc @@ -225,10 +225,12 @@ common::TizenResult IotconServerManager::GetResourceByHandle(iotcon_resource_h r ResourceInfoPtr* res_pointer) const { ScopeLogger(); - auto it = std::find_if(resource_map_.begin(), resource_map_.end(), - [resource](const ResourceInfoMap::value_type& p) -> bool { - return p.second->handle == resource; - }); + auto it = + std::find_if(resource_map_.begin(), resource_map_.end(), + [resource](const ResourceInfoMap::value_type& p) -> bool { + ScopeLogger("Entered into asynchronous function, std::find_if's argument"); + return p.second->handle == resource; + }); if (it == resource_map_.end()) { return LogAndCreateTizenError(NotFoundError, "Resource with specified handle does not exist"); diff --git a/src/iotcon/iotcon_utils.cc b/src/iotcon/iotcon_utils.cc index c616f3d..70546a4 100644 --- a/src/iotcon/iotcon_utils.cc +++ b/src/iotcon/iotcon_utils.cc @@ -244,20 +244,20 @@ TizenResult IotconUtils::InterfacesToArray(iotcon_resource_interfaces_h interfac ScopeLogger(); if (interfaces) { - auto result = ConvertIotconError( - iotcon_resource_interfaces_foreach(interfaces, - [](const char* iface, void* user_data) -> bool { - ScopeLogger("iotcon_resource_interfaces_foreach"); - - if (iface) { - auto arr = static_cast(user_data); - arr->push_back(picojson::value(iface)); - } - - // always continue with iteration - return true; - }, - arr)); + auto result = ConvertIotconError(iotcon_resource_interfaces_foreach( + interfaces, + [](const char* iface, void* user_data) -> bool { + ScopeLogger("Entered into asynchronous function, iotcon_resource_interfaces_foreach"); + + if (iface) { + auto arr = static_cast(user_data); + arr->push_back(picojson::value(iface)); + } + + // always continue with iteration + return true; + }, + arr)); if (!result) { LogAndReturnTizenError(result, ("iotcon_resource_interfaces_foreach() failed")); } @@ -734,6 +734,9 @@ common::TizenResult IotconUtils::RepresentationToJson(iotcon_representation_h re auto result = ConvertIotconError(iotcon_representation_foreach_children( representation, [](iotcon_representation_h child, void* user_data) -> bool { + ScopeLogger( + "Entered into asynchronous function, iotcon_representation_foreach_children's " + "argument"); auto arr = static_cast(user_data); arr->push_back(picojson::value{picojson::object{}}); auto result = RepresentationToJson(child, &arr->back().get()); @@ -764,6 +767,7 @@ common::TizenResult IotconUtils::AttributesToJson(iotcon_attributes_h attributes auto result = ConvertIotconError(iotcon_attributes_foreach( attributes, [](iotcon_attributes_h attributes, const char* key, void* user_data) -> bool { + ScopeLogger("Entered into asynchronous function, iotcon_attributes_foreach's argument"); iotcon_type_e type = IOTCON_TYPE_NONE; auto result = ConvertIotconError(iotcon_attributes_get_type(attributes, key, &type)); @@ -905,62 +909,69 @@ common::TizenResult IotconUtils::StateListToJson(iotcon_list_h list, picojson::a break; case IOTCON_TYPE_INT: - result = ConvertIotconError( - iotcon_list_foreach_int(list, - [](int, int value, void* user_data) -> bool { - auto out = static_cast(user_data); - out->push_back(picojson::value{static_cast(value)}); - // always continue with iteration - return true; - }, - out)); + result = ConvertIotconError(iotcon_list_foreach_int( + list, + [](int, int value, void* user_data) -> bool { + ScopeLogger("Entered into asynchronous function, iotcon_list_foreach_int's argument"); + auto out = static_cast(user_data); + out->push_back(picojson::value{static_cast(value)}); + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_foreach_int() failed")); } break; case IOTCON_TYPE_BOOL: - result = ConvertIotconError( - iotcon_list_foreach_bool(list, - [](int, bool value, void* user_data) -> bool { - auto out = static_cast(user_data); - out->push_back(picojson::value{value}); - // always continue with iteration - return true; - }, - out)); + result = ConvertIotconError(iotcon_list_foreach_bool( + list, + [](int, bool value, void* user_data) -> bool { + ScopeLogger( + "Entered into asynchronous function, iotcon_list_foreach_bool's argument"); + auto out = static_cast(user_data); + out->push_back(picojson::value{value}); + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_foreach_bool() failed")); } break; case IOTCON_TYPE_DOUBLE: - result = ConvertIotconError( - iotcon_list_foreach_double(list, - [](int, double value, void* user_data) -> bool { - auto out = static_cast(user_data); - out->push_back(picojson::value{value}); - // always continue with iteration - return true; - }, - out)); + result = ConvertIotconError(iotcon_list_foreach_double( + list, + [](int, double value, void* user_data) -> bool { + ScopeLogger( + "Entered into asynchronous function, iotcon_list_foreach_double's argument"); + auto out = static_cast(user_data); + out->push_back(picojson::value{value}); + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_foreach_double() failed")); } break; case IOTCON_TYPE_STR: - result = ConvertIotconError( - iotcon_list_foreach_str(list, - [](int, const char* value, void* user_data) -> bool { - if (value) { - auto out = static_cast(user_data); - out->push_back(picojson::value{value}); - } - // always continue with iteration - return true; - }, - out)); + result = ConvertIotconError(iotcon_list_foreach_str( + list, + [](int, const char* value, void* user_data) -> bool { + if (value) { + ScopeLogger( + "Entered into asynchronous function, iotcon_list_foreach_str's argument"); + auto out = static_cast(user_data); + out->push_back(picojson::value{value}); + } + // always continue with iteration + return true; + }, + out)); if (!result) { LogAndReturnTizenError(result, ("iotcon_list_foreach_str() failed")); } @@ -970,6 +981,8 @@ common::TizenResult IotconUtils::StateListToJson(iotcon_list_h list, picojson::a result = ConvertIotconError(iotcon_list_foreach_byte_str( list, [](int, const unsigned char* value, int length, void* user_data) -> bool { + ScopeLogger( + "Entered into asynchronous function, iotcon_list_foreach_byte_str's argument"); if (length) { std::unique_ptr data{new char[2 * length]}; common::tools::BinToHex(value, length, data.get(), 2 * length); @@ -994,6 +1007,8 @@ common::TizenResult IotconUtils::StateListToJson(iotcon_list_h list, picojson::a result = ConvertIotconError(iotcon_list_foreach_list( list, [](int, iotcon_list_h list, void* user_data) -> bool { + ScopeLogger( + "Entered into asynchronous function, iotcon_list_foreach_list's argument"); picojson::value value{picojson::array{}}; auto result = StateListToJson(list, &value.get()); if (result) { @@ -1015,6 +1030,8 @@ common::TizenResult IotconUtils::StateListToJson(iotcon_list_h list, picojson::a result = ConvertIotconError(iotcon_list_foreach_attributes( list, [](int, iotcon_attributes_h attributes, void* user_data) -> bool { + ScopeLogger( + "Entered into asynchronous function, iotcon_list_foreach_attributes' argument"); picojson::value value{picojson::object{}}; auto result = AttributesToJson(attributes, &value.get()); if (result) { @@ -1046,6 +1063,7 @@ common::TizenResult IotconUtils::OptionsToJson(iotcon_options_h options, picojso auto result = ConvertIotconError(iotcon_options_foreach( options, [](unsigned short id, const char* data, void* user_data) -> bool { + ScopeLogger("Entered into asynchronous function, iotcon_options_foreach's argument"); if (data) { picojson::value v{picojson::object{}}; auto& obj = v.get(); @@ -1098,17 +1116,19 @@ common::TizenResult IotconUtils::QueryToJson(iotcon_query_h query, picojson::obj { // filter picojson::value v{picojson::object{}}; - auto result = ConvertIotconError( - iotcon_query_foreach(query, - [](const char* key, const char* value, void* user_data) -> bool { - if (key && value) { - auto obj = static_cast(user_data); - obj->insert(std::make_pair(key, picojson::value{value})); - } - // always continue with iteration - return true; - }, - &v.get())); + auto result = ConvertIotconError(iotcon_query_foreach( + query, + [](const char* key, const char* value, void* user_data) -> bool { + + ScopeLogger("Entered into asynchronous function, iotcon_query_foreach's argument"); + if (key && value) { + auto obj = static_cast(user_data); + obj->insert(std::make_pair(key, picojson::value{value})); + } + // always continue with iteration + return true; + }, + &v.get())); if (!result) { LogAndReturnTizenError(result, ("iotcon_query_foreach() failed")); } diff --git a/src/keymanager/keymanager_instance.cc b/src/keymanager/keymanager_instance.cc index 2f0def1..0e05512 100644 --- a/src/keymanager/keymanager_instance.cc +++ b/src/keymanager/keymanager_instance.cc @@ -45,7 +45,7 @@ typedef int (*AliasListFunction)(ckmc_alias_list_s**); const std::string kSpace = " "; void GetGenericAliasList(AliasListFunction func, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); ckmc_alias_list_s* alias_list = nullptr; int ret = func(&alias_list); @@ -84,7 +84,7 @@ void GetGenericAliasList(AliasListFunction func, picojson::object* out) { } // namespace KeyManagerInstance::KeyManagerInstance() { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -104,7 +104,7 @@ KeyManagerInstance::KeyManagerInstance() { } void KeyManagerInstance::GetDataAliasList(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); GetGenericAliasList(ckmc_get_data_alias_list, &out); } @@ -129,7 +129,7 @@ PlatformResult KeyManagerInstance::GetError(int ret) { } void KeyManagerInstance::SaveData(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); std::string data_raw = args.get("rawData").get(); std::string alias = args.get("aliasName").get(); @@ -145,6 +145,7 @@ void KeyManagerInstance::SaveData(const picojson::value& args, picojson::object& } auto save_data = [data_raw, password, alias](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function, save_data"); unsigned char* data = new unsigned char[data_raw.size()]; std::copy(data_raw.begin(), data_raw.end(), data); @@ -166,6 +167,7 @@ void KeyManagerInstance::SaveData(const picojson::value& args, picojson::object& }; auto save_data_result = [this, callback_id](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function, save_data_result"); result->get()["callbackId"] = picojson::value{callback_id}; Instance::PostMessage(this, result->serialize().c_str()); }; @@ -178,7 +180,7 @@ void KeyManagerInstance::SaveData(const picojson::value& args, picojson::object& } void KeyManagerInstance::GetData(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); const auto& data_alias = args.get("name").get(); const auto& password_value = args.get("password"); @@ -211,11 +213,11 @@ void KeyManagerInstance::GetData(const picojson::value& args, picojson::object& } KeyManagerInstance::~KeyManagerInstance() { - LoggerD("Enter"); + ScopeLogger(); } void KeyManagerInstance::RemoveAlias(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); const std::string& alias = args.get("aliasName").get(); int ret = ckmc_remove_alias(alias.c_str()); @@ -230,7 +232,7 @@ void KeyManagerInstance::RemoveAlias(const picojson::value& args, picojson::obje } void KeyManagerInstance::SetPermission(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); const std::string& data_name = args.get("aliasName").get(); const std::string& id = args.get("packageId").get(); @@ -250,6 +252,8 @@ void KeyManagerInstance::SetPermission(const picojson::value& args, picojson::ob auto set_permissions = [data_name, id, permissions](const std::shared_ptr& response) -> void { + + ScopeLogger("Entered into asynchronous function, set_permissions"); int ret = ckmc_set_permission(data_name.c_str(), id.c_str(), permissions); if (CKMC_ERROR_NONE != ret) { @@ -262,6 +266,7 @@ void KeyManagerInstance::SetPermission(const picojson::value& args, picojson::ob auto set_permissions_response = [this, callback_id](const std::shared_ptr& response) -> void { + ScopeLogger("Entered into asynchronous function, set_permissions_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(this, response->serialize().c_str()); diff --git a/src/mediacontroller/mediacontroller_client.cc b/src/mediacontroller/mediacontroller_client.cc index 59df5aa..55dccb2 100644 --- a/src/mediacontroller/mediacontroller_client.cc +++ b/src/mediacontroller/mediacontroller_client.cc @@ -32,11 +32,11 @@ using common::PlatformResult; using common::ErrorCode; MediaControllerClient::MediaControllerClient() : handle_(nullptr) { - LoggerD("Enter"); + ScopeLogger(); } MediaControllerClient::~MediaControllerClient() { - LoggerD("Enter"); + ScopeLogger(); if (handle_) { int ret = mc_client_destroy(handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { @@ -46,7 +46,7 @@ MediaControllerClient::~MediaControllerClient() { } PlatformResult MediaControllerClient::Init() { - LoggerD("Enter"); + ScopeLogger(); int ret = mc_client_create(&handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { return LogAndCreateResult( @@ -58,7 +58,7 @@ PlatformResult MediaControllerClient::Init() { } PlatformResult MediaControllerClient::FindServers(picojson::array* servers) { - LoggerD("Enter"); + ScopeLogger(); int ret; ret = mc_client_foreach_server(handle_, FindServersCallback, servers); @@ -96,7 +96,7 @@ PlatformResult MediaControllerClient::FindServers(picojson::array* servers) { } bool MediaControllerClient::FindServersCallback(const char* server_name, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::array* servers = static_cast(user_data); picojson::value server = picojson::value(picojson::object()); @@ -111,7 +111,7 @@ bool MediaControllerClient::FindServersCallback(const char* server_name, void* u } PlatformResult MediaControllerClient::GetLatestServerInfo(picojson::value* server_info) { - LoggerD("Enter"); + ScopeLogger(); int ret; char* name = nullptr; @@ -149,7 +149,7 @@ PlatformResult MediaControllerClient::GetLatestServerInfo(picojson::value* serve PlatformResult MediaControllerClient::GetPlaybackInfo(const std::string& server_name, picojson::object* playback_info) { - LoggerD("Enter"); + ScopeLogger(); int ret; mc_playback_h playback_h; @@ -217,7 +217,7 @@ PlatformResult MediaControllerClient::GetPlaybackInfo(const std::string& server_ PlatformResult MediaControllerClient::GetMetadata(const std::string& server_name, picojson::object* metadata) { - LoggerD("Enter"); + ScopeLogger(); int ret; mc_metadata_h metadata_h; @@ -241,7 +241,7 @@ PlatformResult MediaControllerClient::GetMetadata(const std::string& server_name } PlatformResult MediaControllerClient::SetServerStatusChangeListener(JsonCallback callback) { - LoggerD("Enter"); + ScopeLogger(); if (callback && server_status_listener_) { return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "Listener already registered"); } @@ -271,7 +271,7 @@ PlatformResult MediaControllerClient::SetServerStatusChangeListener(JsonCallback void MediaControllerClient::OnServerStatusUpdate(const char* server_name, mc_server_state_e state, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MediaControllerClient* client = static_cast(user_data); if (!client->server_status_listener_) { @@ -298,7 +298,7 @@ void MediaControllerClient::OnServerStatusUpdate(const char* server_name, mc_ser } PlatformResult MediaControllerClient::SetPlaybackInfoListener(JsonCallback callback) { - LoggerD("Enter"); + ScopeLogger(); if (callback && playback_info_listener_) { return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "Listener already registered"); } @@ -372,7 +372,7 @@ PlatformResult MediaControllerClient::SetPlaybackInfoListener(JsonCallback callb void MediaControllerClient::OnPlaybackUpdate(const char* server_name, mc_playback_h playback, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MediaControllerClient* client = static_cast(user_data); if (!client->playback_info_listener_) { @@ -409,7 +409,7 @@ void MediaControllerClient::OnPlaybackUpdate(const char* server_name, mc_playbac void MediaControllerClient::OnShuffleModeUpdate(const char* server_name, mc_shuffle_mode_e mode, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MediaControllerClient* client = static_cast(user_data); if (!client->playback_info_listener_) { @@ -429,7 +429,7 @@ void MediaControllerClient::OnShuffleModeUpdate(const char* server_name, mc_shuf void MediaControllerClient::OnRepeatModeUpdate(const char* server_name, mc_repeat_mode_e mode, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MediaControllerClient* client = static_cast(user_data); if (!client->playback_info_listener_) { @@ -449,7 +449,7 @@ void MediaControllerClient::OnRepeatModeUpdate(const char* server_name, mc_repea void MediaControllerClient::OnMetadataUpdate(const char* server_name, mc_metadata_h metadata_h, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MediaControllerClient* client = static_cast(user_data); if (!client->playback_info_listener_) { @@ -479,7 +479,7 @@ PlatformResult MediaControllerClient::SendCommand(const std::string& server_name const picojson::value& data, const std::string& reply_id, const JsonCallback& reply_cb) { - LoggerD("Enter"); + ScopeLogger(); bundle* bundle = bundle_create(); SCOPE_EXIT { bundle_free(bundle); @@ -515,7 +515,7 @@ PlatformResult MediaControllerClient::SendCommand(const std::string& server_name void MediaControllerClient::OnCommandReply(const char* server_name, int result_code, bundle* bundle, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MediaControllerClient* client = static_cast(user_data); picojson::value reply = picojson::value(picojson::object()); @@ -558,7 +558,7 @@ void MediaControllerClient::OnCommandReply(const char* server_name, int result_c PlatformResult MediaControllerClient::SendPlaybackState(const std::string& server_name, const std::string& state) { - LoggerD("Enter"); + ScopeLogger(); int state_e; PlatformResult result = Types::StringToPlatformEnum(Types::kMediaControllerPlaybackState, state, &state_e); diff --git a/src/mediacontroller/mediacontroller_instance.cc b/src/mediacontroller/mediacontroller_instance.cc index a714734..6f2a961 100644 --- a/src/mediacontroller/mediacontroller_instance.cc +++ b/src/mediacontroller/mediacontroller_instance.cc @@ -41,7 +41,7 @@ using common::PlatformResult; using common::TaskQueue; MediaControllerInstance::MediaControllerInstance() { - LoggerD("Enter"); + ScopeLogger(); using namespace std::placeholders; #define REGISTER_SYNC(c, x) \ @@ -97,7 +97,7 @@ MediaControllerInstance::MediaControllerInstance() { } MediaControllerInstance::~MediaControllerInstance() { - LoggerD("Enter"); + ScopeLogger(); } #define CHECK_EXIST(args, name, out) \ @@ -109,7 +109,7 @@ MediaControllerInstance::~MediaControllerInstance() { void MediaControllerInstance::MediaControllerManagerCreateServer(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMediaControllerServer, &out); @@ -130,7 +130,7 @@ void MediaControllerInstance::MediaControllerManagerCreateServer(const picojson: void MediaControllerInstance::MediaControllerServerUpdatePlaybackState(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "state", out) if (!server_) { @@ -151,7 +151,7 @@ void MediaControllerInstance::MediaControllerServerUpdatePlaybackState(const pic void MediaControllerInstance::MediaControllerServerUpdatePlaybackPosition( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!server_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, ("Failed: server_")); @@ -172,7 +172,7 @@ void MediaControllerInstance::MediaControllerServerUpdatePlaybackPosition( void MediaControllerInstance::MediaControllerServerUpdateShuffleMode(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!server_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, ("Failed: server_")); @@ -194,7 +194,7 @@ void MediaControllerInstance::MediaControllerServerUpdateShuffleMode(const picoj void MediaControllerInstance::MediaControllerServerUpdateRepeatMode(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!server_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, @@ -217,7 +217,7 @@ void MediaControllerInstance::MediaControllerServerUpdateRepeatMode(const picojs void MediaControllerInstance::MediaControllerServerUpdateMetadata(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!server_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, ("Failed: server_")); @@ -239,7 +239,7 @@ void MediaControllerInstance::MediaControllerServerUpdateMetadata(const picojson void MediaControllerInstance::MediaControllerServerAddChangeRequestPlaybackInfoListener( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!server_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, ("Failed: server_")); @@ -267,7 +267,7 @@ void MediaControllerInstance::MediaControllerServerAddChangeRequestPlaybackInfoL void MediaControllerInstance::MediaControllerServerRemoveChangeRequestPlaybackInfoListener( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!server_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, ("Failed: server_")); @@ -279,7 +279,7 @@ void MediaControllerInstance::MediaControllerServerRemoveChangeRequestPlaybackIn void MediaControllerInstance::MediaControllerServerAddCommandListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!server_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, ("Failed: server_")); @@ -300,7 +300,7 @@ void MediaControllerInstance::MediaControllerServerAddCommandListener(const pico void MediaControllerInstance::MediaControllerServerReplyCommand(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!server_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, ("Failed: server_")); @@ -319,7 +319,7 @@ void MediaControllerInstance::MediaControllerServerReplyCommand(const picojson:: void MediaControllerInstance::MediaControllerServerRemoveCommandListener( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!server_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Server not initialized."), &out, ("Failed: server_")); @@ -333,7 +333,7 @@ void MediaControllerInstance::MediaControllerServerRemoveCommandListener( void MediaControllerInstance::MediaControllerManagerGetClient(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMediaControllerClient, &out); @@ -354,7 +354,7 @@ void MediaControllerInstance::MediaControllerManagerGetClient(const picojson::va void MediaControllerInstance::MediaControllerClientFindServers(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!client_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, ("Failed: client_")); @@ -387,7 +387,7 @@ void MediaControllerInstance::MediaControllerClientFindServers(const picojson::v void MediaControllerInstance::MediaControllerClientGetLatestServerInfo(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!client_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, ("Failed: client_")); @@ -406,7 +406,7 @@ void MediaControllerInstance::MediaControllerClientGetLatestServerInfo(const pic void MediaControllerInstance::MediaControllerClientGetPlaybackInfo(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!client_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, ("Failed: client_")); @@ -429,7 +429,7 @@ void MediaControllerInstance::MediaControllerClientGetPlaybackInfo(const picojso void MediaControllerInstance::MediaControllerServerInfoSendPlaybackState( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!client_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, ("Failed: client_")); @@ -464,7 +464,7 @@ void MediaControllerInstance::MediaControllerServerInfoSendPlaybackState( void MediaControllerInstance::MediaControllerServerInfoSendPlaybackPosition( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!client_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, ("Failed: client_")); @@ -499,7 +499,7 @@ void MediaControllerInstance::MediaControllerServerInfoSendPlaybackPosition( void MediaControllerInstance::MediaControllerServerInfoSendShuffleMode(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!client_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, @@ -535,7 +535,7 @@ void MediaControllerInstance::MediaControllerServerInfoSendShuffleMode(const pic void MediaControllerInstance::MediaControllerServerInfoSendRepeatMode(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!client_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, ("Failed: client_")); @@ -570,7 +570,7 @@ void MediaControllerInstance::MediaControllerServerInfoSendRepeatMode(const pico void MediaControllerInstance::MediaControllerServerInfoSendCommand(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!client_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, ("Failed: client_")); @@ -604,7 +604,7 @@ void MediaControllerInstance::MediaControllerServerInfoSendCommand(const picojso void MediaControllerInstance::MediaControllerServerInfoAddServerStatusChangeListener( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!client_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, ("Failed: client_")); @@ -632,7 +632,7 @@ void MediaControllerInstance::MediaControllerServerInfoAddServerStatusChangeList void MediaControllerInstance::MediaControllerServerInfoRemoveServerStatusChangeListener( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!client_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, ("Failed: client_")); @@ -644,7 +644,7 @@ void MediaControllerInstance::MediaControllerServerInfoRemoveServerStatusChangeL void MediaControllerInstance::MediaControllerServerInfoAddPlaybackInfoChangeListener( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (!client_) { LogAndReportError(PlatformResult(ErrorCode::INVALID_STATE_ERR, "Client not initialized."), &out, ("Failed: client_")); diff --git a/src/mediacontroller/mediacontroller_server.cc b/src/mediacontroller/mediacontroller_server.cc index 62416ea..bd88e3f 100644 --- a/src/mediacontroller/mediacontroller_server.cc +++ b/src/mediacontroller/mediacontroller_server.cc @@ -38,11 +38,11 @@ using common::PlatformResult; using common::ErrorCode; MediaControllerServer::MediaControllerServer() : handle_(nullptr) { - LoggerD("Enter"); + ScopeLogger(); } MediaControllerServer::~MediaControllerServer() { - LoggerD("Enter"); + ScopeLogger(); if (handle_) { int ret; @@ -59,7 +59,7 @@ MediaControllerServer::~MediaControllerServer() { } PlatformResult MediaControllerServer::Init() { - LoggerD("Enter"); + ScopeLogger(); int ret = mc_server_create(&handle_); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { @@ -79,7 +79,7 @@ PlatformResult MediaControllerServer::Init() { } PlatformResult MediaControllerServer::SetPlaybackState(const std::string& state) { - LoggerD("Enter"); + ScopeLogger(); int state_int; PlatformResult result = @@ -107,7 +107,7 @@ PlatformResult MediaControllerServer::SetPlaybackState(const std::string& state) } PlatformResult MediaControllerServer::SetPlaybackPosition(double position) { - LoggerD("Enter"); + ScopeLogger(); int ret = mc_server_set_playback_position(handle_, static_cast(position)); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { @@ -127,7 +127,7 @@ PlatformResult MediaControllerServer::SetPlaybackPosition(double position) { } PlatformResult MediaControllerServer::SetShuffleMode(bool mode) { - LoggerD("Enter"); + ScopeLogger(); int ret = mc_server_update_shuffle_mode(handle_, mode ? MC_SHUFFLE_MODE_ON : MC_SHUFFLE_MODE_OFF); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { @@ -140,7 +140,7 @@ PlatformResult MediaControllerServer::SetShuffleMode(bool mode) { } PlatformResult MediaControllerServer::SetRepeatMode(bool mode) { - LoggerD("Enter"); + ScopeLogger(); int ret = mc_server_update_repeat_mode(handle_, mode ? MC_REPEAT_MODE_ON : MC_REPEAT_MODE_OFF); if (ret != MEDIA_CONTROLLER_ERROR_NONE) { @@ -153,7 +153,7 @@ PlatformResult MediaControllerServer::SetRepeatMode(bool mode) { } PlatformResult MediaControllerServer::SetMetadata(const picojson::object& metadata) { - LoggerD("Enter"); + ScopeLogger(); int attribute_int, ret; for (picojson::object::const_iterator i = metadata.begin(); i != metadata.end(); ++i) { @@ -184,7 +184,7 @@ PlatformResult MediaControllerServer::SetMetadata(const picojson::object& metada void MediaControllerServer::OnCommandReceived(const char* client_name, const char* command, bundle* bundle, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MediaControllerServer* server = static_cast(user_data); @@ -259,7 +259,7 @@ void MediaControllerServer::OnCommandReceived(const char* client_name, const cha PlatformResult MediaControllerServer::CommandReply(const std::string& client_name, const std::string& reply_id, const picojson::value& data) { - LoggerD("Enter"); + ScopeLogger(); int ret; @@ -293,7 +293,7 @@ PlatformResult MediaControllerServer::CommandReply(const std::string& client_nam } PlatformResult MediaControllerServer::SetChangeRequestPlaybackInfoListener(JsonCallback callback) { - LoggerD("Enter"); + ScopeLogger(); if (callback && change_request_playback_info_listener_) { return LogAndCreateResult(ErrorCode::INVALID_STATE_ERR, "Listener already registered"); @@ -325,7 +325,7 @@ PlatformResult MediaControllerServer::SetChangeRequestPlaybackInfoListener(JsonC void MediaControllerServer::OnPlaybackStateCommand(const char* client_name, mc_playback_states_e state_e, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MediaControllerServer* server = static_cast(user_data); @@ -354,7 +354,7 @@ void MediaControllerServer::OnPlaybackStateCommand(const char* client_name, void MediaControllerServer::OnPlaybackPositionCommand(const char* client_name, unsigned long long position, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MediaControllerServer* server = static_cast(user_data); @@ -374,7 +374,7 @@ void MediaControllerServer::OnPlaybackPositionCommand(const char* client_name, void MediaControllerServer::OnShuffleModeCommand(const char* client_name, mc_shuffle_mode_e mode, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MediaControllerServer* server = static_cast(user_data); @@ -394,7 +394,7 @@ void MediaControllerServer::OnShuffleModeCommand(const char* client_name, mc_shu void MediaControllerServer::OnRepeatModeCommand(const char* client_name, mc_repeat_mode_e mode, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MediaControllerServer* server = static_cast(user_data); diff --git a/src/mediacontroller/mediacontroller_types.cc b/src/mediacontroller/mediacontroller_types.cc index f54907c..a08aeff 100644 --- a/src/mediacontroller/mediacontroller_types.cc +++ b/src/mediacontroller/mediacontroller_types.cc @@ -61,7 +61,7 @@ PlatformEnumReverseMap Types::platform_enum_reverse_map_ = {}; PlatformResult Types::GetPlatformEnumMap(const std::string& type, std::map* enum_map) { - LoggerD("Enter"); + ScopeLogger(); auto iter = platform_enum_map_.find(type); if (iter == platform_enum_map_.end()) { @@ -76,7 +76,7 @@ PlatformResult Types::GetPlatformEnumMap(const std::string& type, PlatformResult Types::StringToPlatformEnum(const std::string& type, const std::string& value, int* platform_enum) { - LoggerD("Enter"); + ScopeLogger(); std::map def; PlatformResult result = GetPlatformEnumMap(type, &def); @@ -96,7 +96,7 @@ PlatformResult Types::StringToPlatformEnum(const std::string& type, const std::s PlatformResult Types::PlatformEnumToString(const std::string& type, int value, std::string* platform_str) { - LoggerD("Enter"); + ScopeLogger(); if (platform_enum_reverse_map_.empty()) { for (auto& def : platform_enum_map_) { @@ -126,7 +126,7 @@ PlatformResult Types::PlatformEnumToString(const std::string& type, int value, } PlatformResult Types::ConvertPlaybackState(mc_playback_h playback_h, std::string* state) { - LoggerD("Enter"); + ScopeLogger(); int ret; mc_playback_states_e state_e; @@ -151,7 +151,7 @@ PlatformResult Types::ConvertPlaybackState(mc_playback_h playback_h, std::string } PlatformResult Types::ConvertPlaybackPosition(mc_playback_h playback_h, double* position) { - LoggerD("Enter"); + ScopeLogger(); int ret; @@ -169,7 +169,7 @@ PlatformResult Types::ConvertPlaybackPosition(mc_playback_h playback_h, double* } PlatformResult Types::ConvertMetadata(mc_metadata_h metadata_h, picojson::object* metadata) { - LoggerD("Enter"); + ScopeLogger(); std::map metadata_fields; PlatformResult result = diff --git a/src/mediakey/mediakey_instance.cc b/src/mediakey/mediakey_instance.cc index 4a31a1e..69d6915 100644 --- a/src/mediakey/mediakey_instance.cc +++ b/src/mediakey/mediakey_instance.cc @@ -30,7 +30,7 @@ const std::map kMediaKeyTypeMap = { {MEDIA_KEY_REWIND, "MEDIA_REWIND"}, {MEDIA_KEY_PLAYPAUSE, "MEDIA_PLAY_PAUSE"}}; MediaKeyInstance::MediaKeyInstance() { - LoggerD("Entered"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; #define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&MediaKeyInstance::x, this, _1, _2)); @@ -40,13 +40,13 @@ MediaKeyInstance::MediaKeyInstance() { } MediaKeyInstance::~MediaKeyInstance() { - LoggerD("Entered"); + ScopeLogger(); MediaKeyManager::GetInstance().UnregisterMediaKeyEventListener(); } void MediaKeyInstance::SetMediaKeyEventListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); common::PlatformResult result = MediaKeyManager::GetInstance().RegisterMediaKeyEventListener(this); @@ -59,7 +59,7 @@ void MediaKeyInstance::SetMediaKeyEventListener(const picojson::value& args, void MediaKeyInstance::UnsetMediaKeyEventListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); common::PlatformResult result = MediaKeyManager::GetInstance().UnregisterMediaKeyEventListener(); if (result.IsError()) { LogAndReportError(result, &out, ("Failed to remove media key event listener")); @@ -69,17 +69,17 @@ void MediaKeyInstance::UnsetMediaKeyEventListener(const picojson::value& args, } void MediaKeyInstance::OnPressedMediaKeyEventCallback(media_key_e type) { - LoggerD("Enter"); + ScopeLogger(); PostEvent("onPressedMediaKeyEventCallback", type); } void MediaKeyInstance::OnReleasedMediaKeyEventCallback(media_key_e type) { - LoggerD("Enter"); + ScopeLogger(); PostEvent("onReleasedMediaKeyEventCallback", type); } void MediaKeyInstance::PostEvent(const std::string& eventCallback, media_key_e type) { - LoggerD("Enter"); + ScopeLogger(); auto k = kMediaKeyTypeMap.find(type); if (k != kMediaKeyTypeMap.end()) { picojson::value event = picojson::value(picojson::object()); diff --git a/src/mediakey/mediakey_manager.cc b/src/mediakey/mediakey_manager.cc index 0518214..8e8182d 100644 --- a/src/mediakey/mediakey_manager.cc +++ b/src/mediakey/mediakey_manager.cc @@ -24,7 +24,7 @@ namespace mediakey { using common::UnknownException; using common::ErrorCode; MediaKeyListener::~MediaKeyListener() { - LoggerD("Enter"); + ScopeLogger(); } MediaKeyManager& MediaKeyManager::GetInstance() { @@ -34,11 +34,11 @@ MediaKeyManager& MediaKeyManager::GetInstance() { MediaKeyManager::MediaKeyManager() : m_media_key_listener(nullptr), m_media_key_listener_registered(false) { - LoggerD("Enter"); + ScopeLogger(); } common::PlatformResult MediaKeyManager::RegisterMediaKeyEventListener(MediaKeyListener* listener) { - LoggerD("Enter"); + ScopeLogger(); if (!m_media_key_listener_registered) { LoggerD("before calling media_key_reserve"); int ret = media_key_reserve(MediaKeyEventCallback, NULL); @@ -55,7 +55,7 @@ common::PlatformResult MediaKeyManager::RegisterMediaKeyEventListener(MediaKeyLi return common::PlatformResult(ErrorCode::NO_ERROR); } common::PlatformResult MediaKeyManager::UnregisterMediaKeyEventListener() { - LoggerD("Enter"); + ScopeLogger(); if (m_media_key_listener_registered) { int ret = media_key_release(); if (MEDIA_KEY_ERROR_NONE != ret) { @@ -71,7 +71,7 @@ common::PlatformResult MediaKeyManager::UnregisterMediaKeyEventListener() { void MediaKeyManager::MediaKeyEventCallback(media_key_e key, media_key_event_e status, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); if (!GetInstance().m_media_key_listener) { LoggerD("Listener is null. Ignoring"); return; diff --git a/src/messageport/messageport_instance.cc b/src/messageport/messageport_instance.cc index e6d63cd..2614fda 100644 --- a/src/messageport/messageport_instance.cc +++ b/src/messageport/messageport_instance.cc @@ -35,7 +35,7 @@ using common::NotFoundException; using common::QuotaExceededException; MessageportInstance::MessageportInstance() { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; #define REGISTER_SYNC(c, x) \ @@ -53,7 +53,7 @@ MessageportInstance::MessageportInstance() { } MessageportInstance::~MessageportInstance() { - LoggerD("Enter"); + ScopeLogger(); } enum MessageportCallbacks { @@ -68,7 +68,7 @@ enum MessageportCallbacks { static void BundleJsonIterator(const char* key, const int type, const bundle_keyval_t* kv, void* d) { - LoggerD("Enter"); + ScopeLogger(); void* basic_val = nullptr; size_t basic_size = 0; @@ -158,7 +158,7 @@ static void BundleJsonIterator(const char* key, const int type, const bundle_key static void OnReceiveLocalMessage(int local_port_id, const char* remote_app_id, const char* remote_port, bool trusted_remote_port, bundle* message, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); MessageportInstance* object = static_cast(user_data); picojson::value::object o; picojson::value::array data; @@ -183,7 +183,7 @@ static void OnReceiveLocalMessage(int local_port_id, const char* remote_app_id, void MessageportInstance::MessagePortManagerRequestlocalmessageport(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "localMessagePortName", out) int portId; @@ -225,7 +225,7 @@ void MessageportInstance::MessagePortManagerRequestlocalmessageport(const picojs void MessageportInstance::MessagePortManagerRequesttrustedlocalmessageport( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "localMessagePortName", out) int portId; @@ -267,7 +267,7 @@ void MessageportInstance::MessagePortManagerRequesttrustedlocalmessageport( void MessageportInstance::MessagePortManagerRequestremotemessageport(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "remoteMessagePortName", out) const std::string& remoteMessagePortName = args.get("remoteMessagePortName").get(); @@ -314,7 +314,7 @@ void MessageportInstance::MessagePortManagerRequestremotemessageport(const picoj void MessageportInstance::MessagePortManagerRequesttrustedremotemessageport( const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "remoteMessagePortName", out) const std::string& remoteMessagePortName = args.get("remoteMessagePortName").get(); @@ -366,7 +366,7 @@ void MessageportInstance::MessagePortManagerRequesttrustedremotemessageport( void MessageportInstance::RemoteMessagePortSendmessage(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); const std::string& appId = args.get("appId").get(); const std::string& message_port_name = args.get("messagePortName").get(); std::vector data = args.get("data").get(); diff --git a/src/messaging/DBus/EmailSignalProxy.cpp b/src/messaging/DBus/EmailSignalProxy.cpp index 9c6b216..65f4b63 100644 --- a/src/messaging/DBus/EmailSignalProxy.cpp +++ b/src/messaging/DBus/EmailSignalProxy.cpp @@ -32,9 +32,11 @@ EmailSignalProxy::EmailSignalProxy(const std::string& proxy_path, const std::str : common::dbus::Proxy(proxy_path, proxy_iface, kDBusNameSignalEmail, // specify email signal details kDBusPathNetworkStatus, kDBusIfaceNetworkStatus) { + ScopeLogger(); } EmailSignalProxy::~EmailSignalProxy() { + ScopeLogger(); } void EmailSignalProxy::signalCallback(GDBusConnection* connection, const gchar* sender_name, diff --git a/src/messaging/DBus/LoadAttachmentProxy.cpp b/src/messaging/DBus/LoadAttachmentProxy.cpp index 97dea32..95fdaf3 100644 --- a/src/messaging/DBus/LoadAttachmentProxy.cpp +++ b/src/messaging/DBus/LoadAttachmentProxy.cpp @@ -47,8 +47,10 @@ PlatformResult updateAttachmentDataWithEmailGetAttachmentData( std::shared_ptr attachment) { struct ScopedEmailAttachmentData { ScopedEmailAttachmentData() : data(NULL) { + ScopeLogger(); } ~ScopedEmailAttachmentData() { + ScopeLogger(); if (data) { email_free_attachment_data(&data, 1); } @@ -100,13 +102,16 @@ PlatformResult updateAttachmentDataWithEmailGetAttachmentData( LoadAttachmentProxy::LoadAttachmentProxy(const std::string& path, const std::string& iface) : EmailSignalProxy(path, iface) { + ScopeLogger(); } LoadAttachmentProxy::~LoadAttachmentProxy() { + ScopeLogger(); } PlatformResult LoadAttachmentProxy::create(const std::string& path, const std::string& iface, LoadAttachmentProxyPtr* load_attachment_proxy) { + ScopeLogger(); load_attachment_proxy->reset(new LoadAttachmentProxy(path, iface)); if ((*load_attachment_proxy)->isNotProxyGot()) { load_attachment_proxy->reset(); @@ -117,6 +122,7 @@ PlatformResult LoadAttachmentProxy::create(const std::string& path, const std::s } void LoadAttachmentProxy::addCallback(MessageAttachmentCallbackData* callbackOwned) { + ScopeLogger(); if (callbackOwned->getMessageAttachment()) { LoggerD("Registered callback for attachment_id: %d mail_id:%d op_handle:%d nth:%d", callbackOwned->getMessageAttachment()->getId(), @@ -128,6 +134,7 @@ void LoadAttachmentProxy::addCallback(MessageAttachmentCallbackData* callbackOwn } void LoadAttachmentProxy::removeCallback(MessageAttachmentCallbackData* callback) { + ScopeLogger(); if (callback->getMessageAttachment()) { LoggerD("Removed callback for attachment_id: %d mail_id:%d op_handle:%d nth:%d", callback->getMessageAttachment()->getId(), @@ -139,6 +146,7 @@ void LoadAttachmentProxy::removeCallback(MessageAttachmentCallbackData* callback } MessageAttachmentCallbackData* LoadAttachmentProxy::findCallback(const int nth, const int mail_id) { + ScopeLogger(); CallbackSet::iterator it = m_callback_set.begin(); for (; it != m_callback_set.end(); ++it) { MessageAttachmentCallbackData* callback = *it; @@ -154,6 +162,7 @@ MessageAttachmentCallbackData* LoadAttachmentProxy::findCallback(const int nth, void LoadAttachmentProxy::handleEmailSignal(const int status, const int mail_id, const std::string& source, const int op_handle, const int error_code) { + ScopeLogger(); if (NOTI_DOWNLOAD_ATTACH_FINISH != status && NOTI_DOWNLOAD_ATTACH_FAIL != status) { return; } diff --git a/src/messaging/DBus/LoadBodyProxy.cpp b/src/messaging/DBus/LoadBodyProxy.cpp index 944614a..63f77b6 100644 --- a/src/messaging/DBus/LoadBodyProxy.cpp +++ b/src/messaging/DBus/LoadBodyProxy.cpp @@ -49,13 +49,16 @@ using namespace common; LoadBodyProxy::LoadBodyProxy(const std::string& path, const std::string& iface) : EmailSignalProxy(path, iface) { + ScopeLogger(); } LoadBodyProxy::~LoadBodyProxy() { + ScopeLogger(); } PlatformResult LoadBodyProxy::create(const std::string& path, const std::string& iface, LoadBodyProxyPtr* load_body_proxy) { + ScopeLogger(); load_body_proxy->reset(new LoadBodyProxy(path, iface)); if ((*load_body_proxy)->isNotProxyGot()) { load_body_proxy->reset(); @@ -74,6 +77,7 @@ void LoadBodyProxy::removeCallback(MessageBodyCallbackData* callback) { } MessageBodyCallbackData* LoadBodyProxy::findCallbackByOpHandle(const int op_handle) { + ScopeLogger(); CallbackSet::iterator it = m_callback_set.begin(); for (; it != m_callback_set.end(); ++it) { MessageBodyCallbackData* callback = *it; @@ -89,6 +93,7 @@ MessageBodyCallbackData* LoadBodyProxy::findCallbackByOpHandle(const int op_hand void LoadBodyProxy::handleEmailSignal(const int status, const int mail_id, const std::string& source, const int op_handle, const int error_code) { + ScopeLogger(); switch (status) { // We should handle this signal since it is DOWNLOAD_BODY_* case NOTI_DOWNLOAD_BODY_START: diff --git a/src/messaging/DBus/MessageProxy.cpp b/src/messaging/DBus/MessageProxy.cpp index cd3a7d1..7cc1653 100644 --- a/src/messaging/DBus/MessageProxy.cpp +++ b/src/messaging/DBus/MessageProxy.cpp @@ -35,12 +35,15 @@ MessageProxy::MessageProxy() : common::dbus::Proxy(kDBusPathEmailStorageChange, kDBusIfaceEmailStorageChange, kDBusNameSignalEmail, kDBusPathEmailStorageChange, kDBusIfaceEmailStorageChange) { + ScopeLogger(); } MessageProxy::~MessageProxy() { + ScopeLogger(); } PlatformResult MessageProxy::create(MessageProxyPtr* message_proxy) { + ScopeLogger(); message_proxy->reset(new MessageProxy()); if ((*message_proxy)->isNotProxyGot()) { message_proxy->reset(); @@ -53,7 +56,7 @@ PlatformResult MessageProxy::create(MessageProxyPtr* message_proxy) { void MessageProxy::signalCallback(GDBusConnection* connection, const gchar* sender_name, const gchar* object_path, const gchar* interface_name, const gchar* signal_name, GVariant* parameters) { - LoggerD("Enter"); + ScopeLogger(); int status, account_id, object_id, thread_id; char* name; g_variant_get(parameters, "(iiisi)", &status, &account_id, &object_id, &name, &thread_id); @@ -100,7 +103,7 @@ void MessageProxy::signalCallback(GDBusConnection* connection, const gchar* send PlatformResult MessageProxy::handleEmailEvent(int account_id, int mail_id, int thread_id, int event) { - LoggerD("Enter"); + ScopeLogger(); if (ChangeListenerContainer::getInstance().isEmailListenerRegistered()) { LoggerD("Listener registered - perform action"); @@ -175,6 +178,7 @@ PlatformResult MessageProxy::handleEmailEvent(int account_id, int mail_id, int t } std::vector getMailIds(const std::string& idsString) { + ScopeLogger(); std::stringstream idsStream(idsString); std::string item; std::vector ids; @@ -193,7 +197,7 @@ std::vector getMailIds(const std::string& idsString) { } void MessageProxy::handleEmailRemoveEvent(int account_id, const std::string& idsString) { - LoggerD("Enter"); + ScopeLogger(); std::vector ids = getMailIds(idsString); if (ids.empty()) { LoggerD("Mail id list is empty."); @@ -216,7 +220,7 @@ void MessageProxy::handleEmailRemoveEvent(int account_id, const std::string& ids void MessageProxy::notifyEmailManager(const std::string& idsString, email_noti_on_storage_event status) { - LoggerD("Enter"); + ScopeLogger(); std::vector ids = getMailIds(idsString); if (ids.empty()) { LoggerD("Mail id list is empty."); @@ -226,7 +230,7 @@ void MessageProxy::notifyEmailManager(const std::string& idsString, } void MessageProxy::handleThreadRemoveEvent(int account_id, int thread_id) { - LoggerD("Enter"); + ScopeLogger(); // event is called after thread is removed, so we just set thread id and type ConversationPtr conv = std::make_shared(); conv->setConversationId(thread_id); @@ -242,7 +246,7 @@ void MessageProxy::handleThreadRemoveEvent(int account_id, int thread_id) { } PlatformResult MessageProxy::handleMailboxEvent(int account_id, int mailbox_id, int event) { - LoggerD("Enter"); + ScopeLogger(); EventFolders* eventFolder = new EventFolders(); eventFolder->service_type = MessageType::EMAIL; eventFolder->service_id = account_id; diff --git a/src/messaging/DBus/SendProxy.cpp b/src/messaging/DBus/SendProxy.cpp index f747113..0e8dc8e 100644 --- a/src/messaging/DBus/SendProxy.cpp +++ b/src/messaging/DBus/SendProxy.cpp @@ -30,12 +30,15 @@ namespace DBus { using namespace common; SendProxy::SendProxy() : EmailSignalProxy(kDBusPathNetworkStatus, kDBusIfaceNetworkStatus) { + ScopeLogger(); } SendProxy::~SendProxy() { + ScopeLogger(); } PlatformResult SendProxy::create(SendProxyPtr* send_proxy) { + ScopeLogger(); send_proxy->reset(new SendProxy()); if ((*send_proxy)->isNotProxyGot()) { send_proxy->reset(); @@ -47,7 +50,7 @@ PlatformResult SendProxy::create(SendProxyPtr* send_proxy) { void SendProxy::handleEmailSignal(const int status, const int account_id, const std::string& source, const int mail_id, const int error_code) { - LoggerD("Enter"); + ScopeLogger(); switch (status) { case NOTI_SEND_FINISH: case NOTI_SEND_FAIL: diff --git a/src/messaging/DBus/SyncProxy.cpp b/src/messaging/DBus/SyncProxy.cpp index c47b6b2..5ca89fc 100644 --- a/src/messaging/DBus/SyncProxy.cpp +++ b/src/messaging/DBus/SyncProxy.cpp @@ -34,13 +34,16 @@ using namespace common; SyncProxy::SyncProxy(const std::string& path, const std::string& iface) : EmailSignalProxy(path, iface) { + ScopeLogger(); } SyncProxy::~SyncProxy() { + ScopeLogger(); } PlatformResult SyncProxy::create(const std::string& path, const std::string& iface, SyncProxyPtr* sync_proxy) { + ScopeLogger(); sync_proxy->reset(new SyncProxy(path, iface)); if ((*sync_proxy)->isNotProxyGot()) { sync_proxy->reset(); @@ -51,10 +54,12 @@ PlatformResult SyncProxy::create(const std::string& path, const std::string& ifa } void SyncProxy::addCallback(long op_id, CallbackUserData* callbackOwned) { + ScopeLogger(); m_callback_map.insert(std::make_pair(op_id, callbackOwned)); } CallbackUserData* SyncProxy::getCallback(long op_id) { + ScopeLogger(); CallbackUserData* cb = nullptr; const auto it = m_callback_map.find(op_id); @@ -68,6 +73,7 @@ CallbackUserData* SyncProxy::getCallback(long op_id) { } void SyncProxy::removeCallback(long op_id) { + ScopeLogger(); auto it = m_callback_map.find(op_id); if (it != m_callback_map.end()) { delete it->second; @@ -79,6 +85,7 @@ void SyncProxy::removeCallback(long op_id) { void SyncProxy::handleEmailSignal(const int status, const int mail_id, const std::string& source, const int op_handle, const int error_code) { + ScopeLogger(); if (NOTI_DOWNLOAD_START != status && NOTI_DOWNLOAD_FINISH != status && NOTI_DOWNLOAD_FAIL != status) { // Nothing to do: this status is not related to sync nor syncFolder request @@ -132,6 +139,7 @@ void SyncProxy::handleEmailSignal(const int status, const int mail_id, const std PlatformResult SyncProxy::findSyncCallbackByOpHandle(const int op_handle, SyncProxy::CallbackMap::iterator* it) { + ScopeLogger(); *it = m_callback_map.begin(); for (; *it != m_callback_map.end(); ++(*it)) { SyncCallbackData* cb = dynamic_cast((*it)->second); diff --git a/src/messaging/MsgCommon/AbstractFilter.cpp b/src/messaging/MsgCommon/AbstractFilter.cpp index 9cbddb9..3f30d4d 100644 --- a/src/messaging/MsgCommon/AbstractFilter.cpp +++ b/src/messaging/MsgCommon/AbstractFilter.cpp @@ -29,9 +29,11 @@ namespace tizen { using namespace common; AbstractFilter::AbstractFilter(FilterType filter_type) : m_filter_type(filter_type) { + ScopeLogger(); } AbstractFilter::~AbstractFilter() { + ScopeLogger(); } FilterType AbstractFilter::getFilterType() const { @@ -83,6 +85,7 @@ inline std::string convertToLowerCase(const std::string& input_string) { bool FilterUtils::isStringMatching(const std::string& key, const std::string& value, tizen::FilterMatchFlag flag) { + ScopeLogger(); switch (flag) { case tizen::ENDSWITH: { if (key.empty()) { @@ -134,6 +137,7 @@ bool FilterUtils::isStringMatching(const std::string& key, const std::string& va bool FilterUtils::isAnyStringMatching(const std::string& key, const std::vector& values, tizen::FilterMatchFlag flag) { + ScopeLogger(); for (auto it = values.begin(); it != values.end(); ++it) { if (isStringMatching(key, *it, flag)) { return true; @@ -144,6 +148,7 @@ bool FilterUtils::isAnyStringMatching(const std::string& key, bool FilterUtils::isTimeStampInRange(const time_t& time_stamp, tizen::AnyPtr& initial_value, tizen::AnyPtr& end_value) { + ScopeLogger(); time_t from_time = 0; time_t to_time = 0; diff --git a/src/messaging/MsgCommon/Any.cpp b/src/messaging/MsgCommon/Any.cpp index e61087b..23434a0 100644 --- a/src/messaging/MsgCommon/Any.cpp +++ b/src/messaging/MsgCommon/Any.cpp @@ -24,10 +24,12 @@ namespace tizen { Any::Any(picojson::value value) : // m_context(context), m_value(value) { + ScopeLogger(); // JSValueProtect(m_context, m_value); } Any::~Any() { + ScopeLogger(); // JSValueUnprotect(m_context, m_value); } diff --git a/src/messaging/MsgCommon/AttributeFilter.cpp b/src/messaging/MsgCommon/AttributeFilter.cpp index 2342f5c..352c0a8 100644 --- a/src/messaging/MsgCommon/AttributeFilter.cpp +++ b/src/messaging/MsgCommon/AttributeFilter.cpp @@ -23,9 +23,11 @@ namespace tizen { AttributeFilter::AttributeFilter(const std::string &attribute_name) : AbstractFilter(ATTRIBUTE_FILTER), m_attribute_name(attribute_name), m_match_flag(EXACTLY) { + ScopeLogger(); } AttributeFilter::~AttributeFilter() { + ScopeLogger(); } std::string AttributeFilter::getAttributeName() const { @@ -53,6 +55,7 @@ void AttributeFilter::setMatchValue(AnyPtr match_value) { } bool AttributeFilter::isMatching(const FilterableObject *const filtered_object) const { + ScopeLogger(); if (!filtered_object) { LoggerE("Invalid object: NULL!"); return false; diff --git a/src/messaging/MsgCommon/AttributeRangeFilter.cpp b/src/messaging/MsgCommon/AttributeRangeFilter.cpp index 242f3ba..d343767 100644 --- a/src/messaging/MsgCommon/AttributeRangeFilter.cpp +++ b/src/messaging/MsgCommon/AttributeRangeFilter.cpp @@ -23,10 +23,12 @@ namespace tizen { AttributeRangeFilter::AttributeRangeFilter(const std::string &attribute_name) : m_attribute_name(attribute_name) { + ScopeLogger(); m_filter_type = ATTRIBUTE_RANGE_FILTER; } AttributeRangeFilter::~AttributeRangeFilter() { + ScopeLogger(); } std::string AttributeRangeFilter::getAttributeName() const { diff --git a/src/messaging/MsgCommon/CompositeFilter.cpp b/src/messaging/MsgCommon/CompositeFilter.cpp index 3f5b352..d9b4ff7 100644 --- a/src/messaging/MsgCommon/CompositeFilter.cpp +++ b/src/messaging/MsgCommon/CompositeFilter.cpp @@ -27,9 +27,11 @@ CompositeFilter::CompositeFilter(CompositeFilterType type) m_type(type) // m_context(NULL) { + ScopeLogger(); } CompositeFilter::~CompositeFilter() { + ScopeLogger(); } CompositeFilterType CompositeFilter::getType() const { diff --git a/src/messaging/MsgCommon/FilterIterator.cpp b/src/messaging/MsgCommon/FilterIterator.cpp index 4430f7d..2f2ccd0 100644 --- a/src/messaging/MsgCommon/FilterIterator.cpp +++ b/src/messaging/MsgCommon/FilterIterator.cpp @@ -25,6 +25,7 @@ namespace tizen { FilterIterator::FilterIterator(AbstractFilterPtr filter) : m_root_filter(filter), m_current_state(FIS_NOT_VALID) { + ScopeLogger(); if (!m_root_filter) { LoggerE("Trying to create FilterIterator with NULL filter"); m_root_filter = AbstractFilterPtr(new AbstractFilter()); @@ -79,10 +80,12 @@ bool FilterIterator::isLastCompositeSubFilter() const { } void FilterIterator::operator++(int) { + ScopeLogger(); this->operator++(); } void FilterIterator::operator++() { + ScopeLogger(); if (FIS_ATTRIBUTE_FILTER == m_current_state || FIS_ATTRIBUTE_RANGE_FILTER == m_current_state) { if (m_composite_stack.empty()) { // We are not inside composite filter iteration -> reached THE END @@ -109,6 +112,7 @@ void FilterIterator::operator++() { } void FilterIterator::goToNextInCurCompositeFilter() { + ScopeLogger(); CompositeIterState& cur_cs = m_composite_stack.top(); AbstractFilterPtrVector sub_filters = cur_cs.filter->getFilters(); const size_t next_filter_index = cur_cs.cur_sub_filter_index + 1; @@ -124,11 +128,13 @@ void FilterIterator::goToNextInCurCompositeFilter() { } void FilterIterator::setReachedEnd() { + ScopeLogger(); m_current_state = FIS_END; m_current_filter = AbstractFilterPtr(); } void FilterIterator::goToNext(AbstractFilterPtr next) { + ScopeLogger(); switch (next->getFilterType()) { case ATTRIBUTE_FILTER: { m_current_state = FIS_ATTRIBUTE_FILTER; diff --git a/src/messaging/MsgCommon/SortMode.cpp b/src/messaging/MsgCommon/SortMode.cpp index e81b595..4887014 100644 --- a/src/messaging/MsgCommon/SortMode.cpp +++ b/src/messaging/MsgCommon/SortMode.cpp @@ -23,11 +23,12 @@ namespace tizen { SortMode::SortMode(const std::string &attribute_name, SortModeOrder order) : m_attribute_name(attribute_name), m_order(order) { - LoggerD("SortMode attributeName: %s, SortMode order: %s", attribute_name.c_str(), - (order == SortModeOrder::DESC) ? "DESC" : "ASC"); + ScopeLogger("SortMode attributeName: %s, SortMode order: %s", attribute_name.c_str(), + (order == SortModeOrder::DESC) ? "DESC" : "ASC"); } SortMode::~SortMode() { + ScopeLogger(); } std::string SortMode::getAttributeName() const { diff --git a/src/messaging/callback_user_data.cc b/src/messaging/callback_user_data.cc index 4816ce6..dfe796a 100755 --- a/src/messaging/callback_user_data.cc +++ b/src/messaging/callback_user_data.cc @@ -31,7 +31,7 @@ CallbackUserData::CallbackUserData(PostQueue& queue, long cid, bool keep /* = fa cid_(cid), queue_(queue), result_(common::ErrorCode::NO_ERROR) { - LoggerD("Entered"); + ScopeLogger(); if (!keep) { // this is not listener, add callbackId AddJsonData(JSON_CALLBACK_ID, picojson::value(static_cast(cid_))); @@ -39,16 +39,16 @@ CallbackUserData::CallbackUserData(PostQueue& queue, long cid, bool keep /* = fa } CallbackUserData::~CallbackUserData() { - LoggerD("Entered"); + ScopeLogger(); } bool CallbackUserData::IsError() const { - LoggerD("Entered"); + ScopeLogger(); return result_.IsError(); } void CallbackUserData::SetError(const common::PlatformResult& error) { - LoggerD("Entered"); + ScopeLogger(); // keep only the first error if (!IsError()) { ReportError(error, &obj_); @@ -57,7 +57,7 @@ void CallbackUserData::SetError(const common::PlatformResult& error) { } void CallbackUserData::SetSuccess(const picojson::value& data /* = picojson::value()*/) { - LoggerD("Entered"); + ScopeLogger(); // do not allow to overwrite the error if (!IsError()) { ReportSuccess(data, obj_); @@ -65,7 +65,7 @@ void CallbackUserData::SetSuccess(const picojson::value& data /* = picojson::val } void CallbackUserData::SetAction(const char* action, const picojson::value& data) { - LoggerD("Entered"); + ScopeLogger(); AddJsonData(JSON_ACTION, picojson::value(action)); // ReportSuccess cannot be used here, update of this field is necessary (this is a special case) @@ -77,12 +77,12 @@ void CallbackUserData::SetListenerId(const char* id) { } void CallbackUserData::AddToQueue() { - LoggerD("Entered"); + ScopeLogger(); queue_.add(cid_, PostPriority::HIGH); } void CallbackUserData::Post() { - LoggerD("Entered"); + ScopeLogger(); queue_.resolve(cid_, json_.serialize()); } @@ -91,12 +91,12 @@ void CallbackUserData::AddAndPost(PostPriority p) { } bool CallbackUserData::HasQueue(const PostQueue& q) const { - LoggerD("Entered"); + ScopeLogger(); return &q == &queue_; } void CallbackUserData::AddJsonData(const char* key, const picojson::value& value) { - LoggerD("Entered"); + ScopeLogger(); // always overwrite obj_[key] = value; } diff --git a/src/messaging/change_listener_container.cc b/src/messaging/change_listener_container.cc index e530397..e201c8f 100644 --- a/src/messaging/change_listener_container.cc +++ b/src/messaging/change_listener_container.cc @@ -29,7 +29,7 @@ namespace messaging { class ChangeListenerContainer::ChangeListeners { public: ChangeListeners() { - LoggerD("Entered"); + ScopeLogger(); groups_[SMS] = std::shared_ptr(new ListenerGroup()); groups_[MMS] = std::shared_ptr(new ListenerGroup()); @@ -41,7 +41,7 @@ class ChangeListenerContainer::ChangeListeners { template long Add(const std::shared_ptr& c) { - LoggerD("Entered"); + ScopeLogger(); auto it = groups_.find(c->getServiceType()); @@ -54,7 +54,7 @@ class ChangeListenerContainer::ChangeListeners { } void Remove(long id) { - LoggerD("Entered"); + ScopeLogger(); for (auto& it : groups_) { if (it.second->Remove(id)) { @@ -68,7 +68,7 @@ class ChangeListenerContainer::ChangeListeners { template void Call(typename CallbackType::Signature m, EventType* e) const { - LoggerD("Entered"); + ScopeLogger(); auto it = groups_.find(e->service_type); @@ -80,7 +80,7 @@ class ChangeListenerContainer::ChangeListeners { } bool HasListeners(MessageType type) const { - LoggerD("Entered"); + ScopeLogger(); auto it = groups_.find(type); @@ -97,7 +97,7 @@ class ChangeListenerContainer::ChangeListeners { class Listener { public: long Add(const std::shared_ptr& c) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(mutex_); auto id = GetNextId(); @@ -106,7 +106,7 @@ class ChangeListenerContainer::ChangeListeners { } bool Remove(long id) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(mutex_); return (0 != callbacks_.erase(id)); @@ -114,7 +114,7 @@ class ChangeListenerContainer::ChangeListeners { template void Call(typename CallbackType::Signature m, EventType* e) const { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(mutex_); @@ -127,7 +127,7 @@ class ChangeListenerContainer::ChangeListeners { } bool HasListeners() const { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(mutex_); return !callbacks_.empty(); @@ -150,7 +150,7 @@ class ChangeListenerContainer::ChangeListeners { } bool Remove(long id) { - LoggerD("Entered"); + ScopeLogger(); bool ret = false; @@ -166,7 +166,7 @@ class ChangeListenerContainer::ChangeListeners { } bool HasListeners() const { - LoggerD("Entered"); + ScopeLogger(); return message_callbacks_.HasListeners() || conversation_callbacks_.HasListeners() || folder_callbacks_.HasListeners(); } @@ -178,7 +178,7 @@ class ChangeListenerContainer::ChangeListeners { }; static long GetNextId() { - LoggerD("Entered"); + ScopeLogger(); static std::mutex mutex; static long next_id = 0; @@ -210,7 +210,7 @@ ChangeListenerContainer::ChangeListeners::ListenerGroup::Get& callback) { - LoggerD("Entered"); + ScopeLogger(); return listeners_->Add(callback); } long ChangeListenerContainer::addConversationChangeListener( const std::shared_ptr& callback) { - LoggerD("Entered"); + ScopeLogger(); return listeners_->Add(callback); } long ChangeListenerContainer::addFolderChangeListener( const std::shared_ptr& callback) { - LoggerD("Entered"); + ScopeLogger(); return listeners_->Add(callback); } // --- listeners removal --- void ChangeListenerContainer::removeChangeListener(long id) { - LoggerD("Entered"); + ScopeLogger(); listeners_->Remove(id); } // --- Callback invoking functions --- // -- for message -- void ChangeListenerContainer::callMessageAdded(EventMessages* event) const { - LoggerD("Entered"); + ScopeLogger(); listeners_->Call(&MessagesChangeCallback::added, event); } void ChangeListenerContainer::callMessageUpdated(EventMessages* event) const { - LoggerD("Entered"); + ScopeLogger(); listeners_->Call(&MessagesChangeCallback::updated, event); } void ChangeListenerContainer::callMessageRemoved(EventMessages* event) const { - LoggerD("Entered"); + ScopeLogger(); listeners_->Call(&MessagesChangeCallback::removed, event); } // -- for conversation -- void ChangeListenerContainer::callConversationAdded(EventConversations* event) const { - LoggerD("Entered"); + ScopeLogger(); listeners_->Call(&ConversationsChangeCallback::added, event); } void ChangeListenerContainer::callConversationUpdated(EventConversations* event) const { - LoggerD("Entered"); + ScopeLogger(); listeners_->Call(&ConversationsChangeCallback::updated, event); } void ChangeListenerContainer::callConversationRemoved(EventConversations* event) const { - LoggerD("Entered"); + ScopeLogger(); listeners_->Call(&ConversationsChangeCallback::removed, event); } // -- for folder -- void ChangeListenerContainer::callFolderAdded(EventFolders* event) const { - LoggerD("Entered"); + ScopeLogger(); listeners_->Call(&FoldersChangeCallback::added, event); } void ChangeListenerContainer::callFolderUpdated(EventFolders* event) const { - LoggerD("Entered"); + ScopeLogger(); listeners_->Call(&FoldersChangeCallback::updated, event); } void ChangeListenerContainer::callFolderRemoved(EventFolders* event) const { - LoggerD("Entered"); + ScopeLogger(); listeners_->Call(&FoldersChangeCallback::removed, event); } bool ChangeListenerContainer::isEmailListenerRegistered() const { - LoggerD("Entered"); + ScopeLogger(); return listeners_->HasListeners(EMAIL); } diff --git a/src/messaging/conversation_callback_data.cc b/src/messaging/conversation_callback_data.cc index 8f68409..8307092 100644 --- a/src/messaging/conversation_callback_data.cc +++ b/src/messaging/conversation_callback_data.cc @@ -27,11 +27,11 @@ ConversationCallbackData::ConversationCallbackData(PostQueue& queue, long cid, m_offset(0), m_account_id(0), m_service_type(UNDEFINED) { - LoggerD("Entered"); + ScopeLogger(); } ConversationCallbackData::~ConversationCallbackData() { - LoggerD("Entered"); + ScopeLogger(); } void ConversationCallbackData::setFilter(AbstractFilterPtr filter) { diff --git a/src/messaging/conversations_change_callback.cc b/src/messaging/conversations_change_callback.cc index e84428f..91620a4 100644 --- a/src/messaging/conversations_change_callback.cc +++ b/src/messaging/conversations_change_callback.cc @@ -44,17 +44,17 @@ ConversationsChangeCallback::ConversationsChangeCallback(long cid, int service_i m_id(service_id), m_msg_type(service_type), m_is_act(true) { - LoggerD("Entered"); + ScopeLogger(); m_callback_data.SetListenerId("ConversationsChangeListener"); } ConversationsChangeCallback::~ConversationsChangeCallback() { - LoggerD("Entered"); + ScopeLogger(); } ConversationPtrVector ConversationsChangeCallback::filterConversations( AbstractFilterPtr filter, const ConversationPtrVector& source_conversations) { - LoggerD("Entered"); + ScopeLogger(); if (filter) { LoggerD("filter pointer is valid"); ConversationPtrVector filtered_conversations; @@ -84,7 +84,7 @@ ConversationPtrVector ConversationsChangeCallback::filterConversations( } void ConversationsChangeCallback::added(const ConversationPtrVector& conversations) { - LoggerD("Entered conversations.size()=%d", conversations.size()); + ScopeLogger("conversations.size() = %d", conversations.size()); if (!m_is_act) { return; } @@ -110,7 +110,7 @@ void ConversationsChangeCallback::added(const ConversationPtrVector& conversatio } void ConversationsChangeCallback::updated(const ConversationPtrVector& conversations) { - LoggerD("Entered conversations.size()=%d", conversations.size()); + ScopeLogger("conversations.size() = %d", conversations.size()); if (!m_is_act) { return; } @@ -136,7 +136,7 @@ void ConversationsChangeCallback::updated(const ConversationPtrVector& conversat } void ConversationsChangeCallback::removed(const ConversationPtrVector& conversations) { - LoggerD("Entered conversations.size()=%d", conversations.size()); + ScopeLogger("conversations.size() = %d", conversations.size()); if (!m_is_act) { return; } diff --git a/src/messaging/email_manager.cc b/src/messaging/email_manager.cc index 753c752..3bdb55c 100644 --- a/src/messaging/email_manager.cc +++ b/src/messaging/email_manager.cc @@ -72,11 +72,11 @@ const std::string FIND_FOLDERS_ATTRIBUTE_ACCOUNTID_NAME = "serviceId"; } // anonymous namespace EmailManager::EmailManager() : m_slot_size(-1), m_is_initialized(false) { - LoggerD("Entered"); + ScopeLogger(); } EmailManager& EmailManager::getInstance() { - LoggerD("Entered"); + ScopeLogger(); static EmailManager instance; return instance; } @@ -88,7 +88,7 @@ EmailManager& EmailManager::getInstance() { } PlatformResult EmailManager::InitializeEmailService() { - LoggerD("Entered"); + ScopeLogger(); EmailManager& instance = EmailManager::getInstance(); if (!instance.m_is_initialized) { @@ -162,23 +162,24 @@ PlatformResult EmailManager::InitializeEmailService() { } EmailManager::~EmailManager() { - LoggerD("Entered"); + ScopeLogger(); } PlatformResult EmailManager::addDraftMessagePlatform(int account_id, std::shared_ptr message) { - LoggerD("Entered"); + ScopeLogger(); return addMessagePlatform(account_id, message, EMAIL_MAILBOX_TYPE_DRAFT); } PlatformResult EmailManager::addOutboxMessagePlatform(int account_id, std::shared_ptr message) { + ScopeLogger(); return addMessagePlatform(account_id, message, EMAIL_MAILBOX_TYPE_OUTBOX); } PlatformResult EmailManager::addMessagePlatform(int account_id, std::shared_ptr message, email_mailbox_type_e mailbox_type) { - LoggerD("Entered"); + ScopeLogger(); email_mail_data_t* mail_data = NULL; email_mail_data_t* mail_data_final = NULL; int err = EMAIL_ERROR_NONE; @@ -300,7 +301,7 @@ PlatformResult EmailManager::addMessagePlatform(int account_id, std::shared_ptr< } static gboolean addDraftMessageCompleteCB(void* data) { - LoggerD("Entered"); + ScopeLogger(); MessageCallbackUserData* callback = static_cast(data); if (!callback) { LoggerE("Callback is null"); @@ -327,7 +328,7 @@ static gboolean addDraftMessageCompleteCB(void* data) { } void EmailManager::addDraftMessage(MessageCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -351,7 +352,7 @@ void EmailManager::addDraftMessage(MessageCallbackUserData* callback) { //**** sending email **** static gboolean sendEmailCompleteCB(void* data) { - LoggerD("Entered"); + ScopeLogger(); MessageRecipientsCallbackData* callback = static_cast(data); if (!callback) { @@ -396,7 +397,7 @@ static gboolean sendEmailCompleteCB(void* data) { } PlatformResult EmailManager::sendMessage(MessageRecipientsCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); @@ -470,7 +471,7 @@ PlatformResult EmailManager::sendMessage(MessageRecipientsCallbackData* callback void EmailManager::sendStatusCallback(int mail_id, email_noti_on_network_event status, int error_code) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(m_mutex); // find first request for this mail_id @@ -517,7 +518,7 @@ void EmailManager::sendStatusCallback(int mail_id, email_noti_on_network_event s } email_mail_data_t* EmailManager::loadMessage(int msg_id) { - LoggerD("Entered"); + ScopeLogger(); email_mail_data_t* mail_data = NULL; int err = email_get_mail_data(msg_id, &mail_data); if (EMAIL_ERROR_NONE != err) { @@ -529,7 +530,7 @@ email_mail_data_t* EmailManager::loadMessage(int msg_id) { } EmailManager::SendReqMapIterator EmailManager::getSendRequest(int mail_id) { - LoggerD("Entered"); + ScopeLogger(); for (auto it = m_sendRequests.begin(); it != m_sendRequests.end(); it++) { if (it->second->getMessage()->getId() == mail_id) { return it; @@ -539,7 +540,7 @@ EmailManager::SendReqMapIterator EmailManager::getSendRequest(int mail_id) { } void EmailManager::freeMessage(email_mail_data_t* mail_data) { - LoggerD("Entered"); + ScopeLogger(); if (!mail_data) { return; } @@ -551,7 +552,7 @@ void EmailManager::freeMessage(email_mail_data_t* mail_data) { } void EmailManager::loadMessageBody(MessageBodyCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); return; @@ -577,7 +578,7 @@ void EmailManager::loadMessageBody(MessageBodyCallbackData* callback) { } PlatformResult EmailManager::loadMessageAttachment(MessageAttachmentCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Callback is null"); @@ -651,7 +652,7 @@ PlatformResult EmailManager::loadMessageAttachment(MessageAttachmentCallbackData //#################################### sync: ################################### void EmailManager::sync(void* data) { - LoggerD("Entered"); + ScopeLogger(); SyncCallbackData* callback = static_cast(data); @@ -698,7 +699,7 @@ void EmailManager::sync(void* data) { //################################## syncFolder: ############################### void EmailManager::syncFolder(SyncFolderCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -768,7 +769,7 @@ void EmailManager::syncFolder(SyncFolderCallbackData* callback) { //################################## stopSync: ################################# void EmailManager::stopSync(long op_id) { - LoggerD("Entered"); + ScopeLogger(); SyncCallbackData* callback = static_cast(m_proxy_sync->getCallback(op_id)); @@ -793,12 +794,12 @@ void EmailManager::stopSync(long op_id) { //################################## ^stopSync ################################# void EmailManager::RemoveSyncCallback(long op_id) { - LoggerD("Entered"); + ScopeLogger(); m_proxy_sync->removeCallback(op_id); } void EmailManager::RemoveCallbacksByQueue(const PostQueue& q) { - LoggerD("Entered"); + ScopeLogger(); for (auto it = m_sendRequests.begin(); it != m_sendRequests.end();) { if (it->second->HasQueue(q)) { @@ -811,7 +812,7 @@ void EmailManager::RemoveCallbacksByQueue(const PostQueue& q) { } void removeEmailCompleteCB(MessagesCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); return; @@ -834,7 +835,7 @@ void removeEmailCompleteCB(MessagesCallbackUserData* callback) { EmailManager::DeleteReqVector::iterator EmailManager::getDeleteRequest( const std::vector& ids) { - LoggerD("Entered"); + ScopeLogger(); for (auto idIt = ids.begin(); idIt != ids.end(); ++idIt) { for (auto reqIt = m_deleteRequests.begin(); reqIt != m_deleteRequests.end(); ++reqIt) { MessagePtrVector msgs = reqIt->callback->getMessages(); @@ -850,7 +851,7 @@ EmailManager::DeleteReqVector::iterator EmailManager::getDeleteRequest( void EmailManager::removeStatusCallback(const std::vector& ids, email_noti_on_storage_event status) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(m_mutex); DeleteReqVector::iterator it = getDeleteRequest(ids); if (it != m_deleteRequests.end()) { @@ -881,7 +882,7 @@ void EmailManager::removeStatusCallback(const std::vector& ids, } PlatformResult EmailManager::RemoveMessagesPlatform(MessagesCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); int error; email_mail_data_t* mail = NULL; @@ -922,7 +923,7 @@ PlatformResult EmailManager::RemoveMessagesPlatform(MessagesCallbackUserData* ca } void EmailManager::removeMessages(MessagesCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -938,7 +939,7 @@ void EmailManager::removeMessages(MessagesCallbackUserData* callback) { } PlatformResult EmailManager::UpdateMessagesPlatform(MessagesCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); int error; email_mail_data_t* mail = NULL; SCOPE_EXIT { @@ -1000,7 +1001,7 @@ PlatformResult EmailManager::UpdateMessagesPlatform(MessagesCallbackUserData* ca } void EmailManager::updateMessages(MessagesCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -1035,7 +1036,7 @@ void EmailManager::updateMessages(MessagesCallbackUserData* callback) { } PlatformResult EmailManager::FindMessagesPlatform(FindMsgCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); email_mail_data_t* mailList = NULL; int mailListCount = 0; @@ -1068,7 +1069,7 @@ PlatformResult EmailManager::FindMessagesPlatform(FindMsgCallbackUserData* callb } void EmailManager::findMessages(FindMsgCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -1106,7 +1107,7 @@ void EmailManager::findMessages(FindMsgCallbackUserData* callback) { } PlatformResult EmailManager::FindConversationsPlatform(ConversationCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); int convListCount = 0; std::lock_guard lock(m_mutex); @@ -1130,7 +1131,7 @@ PlatformResult EmailManager::FindConversationsPlatform(ConversationCallbackData* } void EmailManager::findConversations(ConversationCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -1169,7 +1170,7 @@ void EmailManager::findConversations(ConversationCallbackData* callback) { } long EmailManager::getUniqueOpId() { - LoggerD("Entered"); + ScopeLogger(); // mutex is created only on first call (first call added to constructor // to initialize mutex correctly) static std::mutex op_id_mutex; @@ -1179,7 +1180,7 @@ long EmailManager::getUniqueOpId() { } PlatformResult EmailManager::FindFoldersPlatform(FoldersCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); int ret = EMAIL_ERROR_UNKNOWN; int account_id = ACCOUNT_ID_NOT_INITIALIZED; email_mailbox_t* mailboxes = NULL; @@ -1249,7 +1250,7 @@ PlatformResult EmailManager::FindFoldersPlatform(FoldersCallbackData* callback) } void EmailManager::findFolders(FoldersCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -1288,7 +1289,7 @@ void EmailManager::findFolders(FoldersCallbackData* callback) { } PlatformResult EmailManager::RemoveConversationsPlatform(ConversationCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); int error; std::lock_guard lock(m_mutex); std::vector> conversations = callback->getConversations(); @@ -1331,7 +1332,7 @@ PlatformResult EmailManager::RemoveConversationsPlatform(ConversationCallbackDat } void EmailManager::removeConversations(ConversationCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -1359,7 +1360,7 @@ void EmailManager::removeConversations(ConversationCallbackData* callback) { } std::string EmailManager::getMessageStatus(int id) { - LoggerD("Entered"); + ScopeLogger(); email_mail_data_t* mail = nullptr; MessageStatus status = MessageStatus::STATUS_UNDEFINED; diff --git a/src/messaging/find_msg_callback_user_data.cc b/src/messaging/find_msg_callback_user_data.cc index bd28ba4..2b309a2 100644 --- a/src/messaging/find_msg_callback_user_data.cc +++ b/src/messaging/find_msg_callback_user_data.cc @@ -29,11 +29,11 @@ FindMsgCallbackUserData::FindMsgCallbackUserData(PostQueue& queue, long cid) m_offset(0), m_account_id(0), m_service_type(UNDEFINED) { - LoggerD("Entered"); + ScopeLogger(); } FindMsgCallbackUserData::~FindMsgCallbackUserData() { - LoggerD("Entered"); + ScopeLogger(); } void FindMsgCallbackUserData::setFilter(AbstractFilterPtr filter) { diff --git a/src/messaging/folders_callback_data.cc b/src/messaging/folders_callback_data.cc index 6d5f3da..a6ba2e6 100644 --- a/src/messaging/folders_callback_data.cc +++ b/src/messaging/folders_callback_data.cc @@ -20,10 +20,11 @@ namespace extension { namespace messaging { FoldersCallbackData::~FoldersCallbackData() { - LoggerD("Entered"); + ScopeLogger(); } void FoldersCallbackData::addFolder(std::shared_ptr folder) { + ScopeLogger(); m_folders.push_back(folder); } diff --git a/src/messaging/folders_change_callback.cc b/src/messaging/folders_change_callback.cc index 7211313..59c159b 100644 --- a/src/messaging/folders_change_callback.cc +++ b/src/messaging/folders_change_callback.cc @@ -33,17 +33,17 @@ FoldersChangeCallback::FoldersChangeCallback(long cid, int service_id, MessageTy m_id(service_id), m_msg_type(service_type), m_is_act(true) { - LoggerD("Entered"); + ScopeLogger(); m_callback_data.SetListenerId("FoldersChangeListener"); } FoldersChangeCallback::~FoldersChangeCallback() { - LoggerD("Entered"); + ScopeLogger(); } FolderPtrVector FoldersChangeCallback::filterFolders(tizen::AbstractFilterPtr filter, const FolderPtrVector& source_folders) { - LoggerD("Entered"); + ScopeLogger(); if (filter) { LoggerD("filter pointer is valid"); FolderPtrVector filtered_folders; @@ -69,7 +69,7 @@ FolderPtrVector FoldersChangeCallback::filterFolders(tizen::AbstractFilterPtr fi } void FoldersChangeCallback::added(const FolderPtrVector& folders) { - LoggerD("Entered folders.size()=%d", folders.size()); + ScopeLogger("folders.size() = %d", folders.size()); if (!m_is_act) { return; } @@ -95,7 +95,7 @@ void FoldersChangeCallback::added(const FolderPtrVector& folders) { } void FoldersChangeCallback::updated(const FolderPtrVector& folders) { - LoggerD("Entered folders.size()=%d", folders.size()); + ScopeLogger("folders.size() = %d", folders.size()); if (!m_is_act) { return; } @@ -121,7 +121,7 @@ void FoldersChangeCallback::updated(const FolderPtrVector& folders) { } void FoldersChangeCallback::removed(const FolderPtrVector& folders) { - LoggerD("Entered folders.size()=%d", folders.size()); + ScopeLogger("folders.size() = %d", folders.size()); if (!m_is_act) { return; } diff --git a/src/messaging/message.cc b/src/messaging/message.cc index 2a10840..a171c9a 100644 --- a/src/messaging/message.cc +++ b/src/messaging/message.cc @@ -63,11 +63,11 @@ Message::Message() m_service_id_set(false), m_status(STATUS_UNDEFINED), m_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN) { - LoggerD("Message constructor (%p)", this); + ScopeLogger("Message constructor (%p)", this); } Message::~Message() { - LoggerD("Message destructor (%p)", this); + ScopeLogger("Message destructor (%p)", this); } // *** attribute getters @@ -87,12 +87,11 @@ int Message::getConversationId() const { } int Message::getFolderId() const { - LoggerD("Entered"); return m_folder_id; } int Message::getFolderIdForUser() const { - LoggerD("Entered"); + ScopeLogger(); // WIDL states: // For SMS and MMS, folderId can be one of these values: // - INBOX = 1, @@ -190,7 +189,7 @@ TelNetworkDefaultDataSubs_t Message::getSimIndex() const { // *** attributes setters void Message::setId(int id) { - LoggerD("Entered"); + ScopeLogger(); m_id = id; m_id_set = true; m_body->setMessageId(m_id); @@ -200,18 +199,18 @@ void Message::setId(int id) { } void Message::setOldId(int id) { - LoggerD("Entered"); + ScopeLogger(); m_old_id = id; } void Message::setConversationId(int id) { - LoggerD("Entered"); + ScopeLogger(); m_conversation_id = id; m_conversation_id_set = true; } void Message::setFolderId(int id) { - LoggerD("Entered"); + ScopeLogger(); m_folder_id = id; m_folder_id_set = true; } @@ -219,19 +218,19 @@ void Message::setFolderId(int id) { // type setting not allowed - no setter for type void Message::setTimeStamp(time_t timestamp) { - LoggerD("Entered"); + ScopeLogger(); m_timestamp = timestamp; m_timestamp_set = true; } void Message::setFrom(std::string from) { - LoggerD("Entered"); + ScopeLogger(); m_from = from; m_from_set = true; } void Message::setTO(std::vector& to) { - LoggerD("Entered"); + ScopeLogger(); // Recipient's format validation should be done by Core API service m_to = to; @@ -250,7 +249,6 @@ void Message::setBCC(std::vector& bcc) { } void Message::setBody(std::shared_ptr& body) { - LoggerD("Entered"); // while replacing message body old body should have some invalid id mark m_body->setMessageId(-1); @@ -261,14 +259,12 @@ void Message::setBody(std::shared_ptr& body) { } void Message::setIsRead(bool read) { - LoggerD("Entered"); m_is_read = read; } // has attachment can't be set explicity -> no setter for this flag void Message::setIsHighPriority(bool highpriority) { - LoggerD("Entered"); // High priority field is used only in MessageEmail m_high_priority = highpriority; } @@ -278,13 +274,11 @@ void Message::setSubject(std::string subject) { } void Message::setInResponseTo(int inresp) { - LoggerD("Entered"); m_in_response = inresp; m_in_response_set = true; } void Message::setMessageStatus(MessageStatus status) { - LoggerD("Entered"); m_status = status; } @@ -293,13 +287,11 @@ void Message::setMessageAttachments(AttachmentPtrVector& attachments) { } void Message::setServiceId(int service_id) { - LoggerD("Entered"); m_service_id = service_id; m_service_id_set = true; } void Message::setSimIndex(TelNetworkDefaultDataSubs_t sim_index) { - LoggerD("Entered"); m_sim_index = sim_index; } @@ -333,7 +325,7 @@ bool Message::is_service_is_set() const { } std::string Message::convertEmailRecipients(const std::vector& recipients) { - LoggerD("Entered"); + ScopeLogger(); std::string address = ""; unsigned size = recipients.size(); for (unsigned i = 0; i < size; ++i) { @@ -344,7 +336,7 @@ std::string Message::convertEmailRecipients(const std::vector& reci } PlatformResult saveToTempFile(const std::string& data, std::string* file_name) { - LoggerD("Entered"); + ScopeLogger(); char buf[] = "XXXXXX"; mode_t mask = umask(S_IWGRP | S_IWOTH); @@ -371,7 +363,7 @@ PlatformResult saveToTempFile(const std::string& data, std::string* file_name) { } PlatformResult copyFileToTemp(const std::string& sourcePath, std::string* result_path) { - LoggerD("Entered"); + ScopeLogger(); char buf[] = "XXXXXX"; std::string fileName, attPath, tmpPath; @@ -436,7 +428,7 @@ PlatformResult copyFileToTemp(const std::string& sourcePath, std::string* result } PlatformResult removeDirFromTemp(const std::string& dirPath) { - LoggerD("Entered"); + ScopeLogger(); if (EINA_TRUE != ecore_file_recursive_rm(dirPath.c_str())) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Unknown error while deleting temp directory."); @@ -446,7 +438,7 @@ PlatformResult removeDirFromTemp(const std::string& dirPath) { PlatformResult Message::convertPlatformEmail(std::shared_ptr message, email_mail_data_t** result_mail_data) { - LoggerD("Entered"); + ScopeLogger(); email_mail_data_t* mail_data = nullptr; if (EMAIL != message->getType()) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Invalid type."); @@ -540,7 +532,7 @@ PlatformResult Message::convertPlatformEmail(std::shared_ptr message, PlatformResult addSingleEmailAttachment(std::shared_ptr message, std::shared_ptr att, AttachmentType attType) { - LoggerD("Entered"); + ScopeLogger(); std::string dirPath = ""; PlatformResult ret = copyFileToTemp(att->getFilePath(), &dirPath); if (ret.IsError()) return ret; @@ -580,7 +572,7 @@ PlatformResult addSingleEmailAttachment(std::shared_ptr message, } PlatformResult Message::addEmailAttachments(std::shared_ptr message) { - LoggerD("Entered"); + ScopeLogger(); int attachment_data_count = 0, error; email_mail_data_t* mail = NULL; @@ -662,7 +654,7 @@ PlatformResult Message::addEmailAttachments(std::shared_ptr message) { PlatformResult Message::addSMSRecipientsToStruct(const std::vector& recipients, msg_struct_t& msg) { - LoggerD("Entered"); + ScopeLogger(); const unsigned size = recipients.size(); for (unsigned int i = 0; i < size; ++i) { char* address = const_cast(recipients.at(i).c_str()); @@ -683,7 +675,7 @@ PlatformResult Message::addSMSRecipientsToStruct(const std::vector& PlatformResult Message::addMMSRecipientsToStruct(const std::vector& recipients, msg_struct_t& msg, int type) { - LoggerD("Entered"); + ScopeLogger(); const unsigned size = recipients.size(); for (unsigned int i = 0; i < size; ++i) { msg_struct_t tmpAddr = NULL; @@ -712,7 +704,7 @@ PlatformResult Message::addMMSRecipientsToStruct(const std::vector& PlatformResult Message::addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVector& attach, msg_struct_t& mms_struct, Message* message) { - LoggerD("Entered with %d attachments", attach.size()); + ScopeLogger("attachments.size() = %zd", attach.size()); int size = attach.size(); for (int i = 0; i < size; i++) { @@ -779,7 +771,7 @@ PlatformResult Message::addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVect PlatformResult Message::convertPlatformShortMessageToStruct(Message* message, msg_handle_t handle, msg_struct_t* result_msg) { - LoggerD("Entered"); + ScopeLogger(); int ntv_ret = 0; @@ -1023,14 +1015,13 @@ PlatformResult Message::convertPlatformShortMessageToStruct(Message* message, ms // Set message if is read msg_set_bool_value(msg, MSG_MESSAGE_READ_BOOL, message->getIsRead()); - LoggerD("End"); *result_msg = msg; msg_ptr.release(); // release ownership return PlatformResult(ErrorCode::NO_ERROR); } std::string Message::getShortMsgSenderFromStruct(msg_struct_t& msg) { - LoggerD("Entered"); + ScopeLogger(); msg_list_handle_t addr_list = NULL; msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND, (void**)&addr_list); @@ -1063,7 +1054,7 @@ std::string Message::getShortMsgSenderFromStruct(msg_struct_t& msg) { PlatformResult Message::getSMSRecipientsFromStruct(msg_struct_t& msg, std::vector* result_address) { - LoggerD("Entered"); + ScopeLogger(); std::vector address; msg_list_handle_t addr_list = NULL; int ntv_ret = msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND, (void**)&addr_list); @@ -1089,7 +1080,7 @@ PlatformResult Message::getSMSRecipientsFromStruct(msg_struct_t& msg, PlatformResult Message::getMMSRecipientsFromStruct(msg_struct_t& msg, int type, std::vector* result_address) { - LoggerD("Entered"); + ScopeLogger(); std::vector address; msg_list_handle_t addr_list = NULL; int ntv_ret = msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND, (void**)&addr_list); @@ -1118,7 +1109,7 @@ PlatformResult Message::getMMSRecipientsFromStruct(msg_struct_t& msg, int type, } PlatformResult Message::setMMSBodyAndAttachmentsFromStruct(Message* message, msg_struct_t& msg) { - LoggerD("Entered message(%p)", message); + ScopeLogger("message(%p)", message); int tempInt = 0; char infoStr[MSG_FILEPATH_LEN_MAX + 1]; @@ -1289,7 +1280,7 @@ PlatformResult Message::setMMSBodyAndAttachmentsFromStruct(Message* message, msg PlatformResult Message::convertPlatformShortMessageToObject(msg_struct_t msg, Message** result_message) { - LoggerD("Entered"); + ScopeLogger(); std::unique_ptr message; int infoInt; bool infoBool; @@ -1486,7 +1477,7 @@ PlatformResult Message::convertPlatformShortMessageToObject(msg_struct_t msg, } PlatformResult Message::findShortMessageById(const int id, MessagePtr* message) { - LoggerD("Entered"); + ScopeLogger(); msg_struct_t msg; PlatformResult ret = ShortMsgManager::getInstance().getMessage(id, &msg); if (ret.IsError()) { @@ -1503,7 +1494,7 @@ PlatformResult Message::findShortMessageById(const int id, MessagePtr* message) } std::vector Message::split(const std::string& input, char delimiter) { - LoggerD("Entered"); + ScopeLogger(); std::vector ret; std::stringstream stream(input); std::string item; @@ -1514,7 +1505,7 @@ std::vector Message::split(const std::string& input, char delimiter } std::vector Message::getEmailRecipientsFromStruct(const char* recipients) { - LoggerD("Entered"); + ScopeLogger(); std::vector tmp = Message::split(recipients, ';'); for (std::vector::iterator it = tmp.begin(); it != tmp.end(); ++it) { *it = MessagingUtil::ltrim(*it); @@ -1536,7 +1527,7 @@ std::vector Message::getEmailRecipientsFromStruct(const char* recip } std::shared_ptr Message::convertEmailToMessageBody(email_mail_data_t& mail) { - LoggerD("Entered"); + ScopeLogger(); std::shared_ptr body(new MessageBody()); body->updateBody(mail); return body; @@ -1544,7 +1535,7 @@ std::shared_ptr Message::convertEmailToMessageBody(email_mail_data_ PlatformResult Message::convertEmailToMessageAttachment(email_mail_data_t& mail, AttachmentPtrVector* att) { - LoggerD("Entered"); + ScopeLogger(); email_attachment_data_t* attachment = NULL; int attachmentCount = 0; @@ -1568,7 +1559,7 @@ PlatformResult Message::convertEmailToMessageAttachment(email_mail_data_t& mail, PlatformResult Message::convertPlatformEmailToObject(email_mail_data_t& mail, std::shared_ptr* result) { - LoggerD("Entered"); + ScopeLogger(); Message* message = new MessageEmail(); PlatformResult ret = message->updateEmailMessage(mail); if (ret.IsError()) { @@ -1629,7 +1620,7 @@ const std::string SUBJECT = MESSAGE_ATTRIBUTE_SUBJECT; bool Message::isMatchingAttribute(const std::string& attribute_name, const FilterMatchFlag match_flag, AnyPtr match_value) const { - LoggerD("Entered"); + ScopeLogger(); auto key = match_value->toString(); LoggerD("attribute_name:%s match_flag:%d matchValue:%s", attribute_name.c_str(), match_flag, key.c_str()); @@ -1677,7 +1668,7 @@ bool Message::isMatchingAttribute(const std::string& attribute_name, bool Message::isMatchingAttributeRange(const std::string& attribute_name, AnyPtr initial_value, AnyPtr end_value) const { - LoggerD("Entered attribute_name: %s", attribute_name.c_str()); + ScopeLogger(attribute_name); using namespace MESSAGE_FILTER_ATTRIBUTE; if (TIMESTAMP == attribute_name) { diff --git a/src/messaging/message_attachment.cc b/src/messaging/message_attachment.cc index 07972e9..56558a9 100644 --- a/src/messaging/message_attachment.cc +++ b/src/messaging/message_attachment.cc @@ -31,7 +31,7 @@ std::map& MessageAttachment::MIMETypeEnumToStringMap initializeMIMETypeEnumToStringMap(); MessageAttachment::MessageAttachment() { - LoggerD("MessageAttachment constructor (%p)", this); + ScopeLogger("MessageAttachment constructor (%p)", this); m_id = -1; m_isIdSet = false; m_messageId = -1; @@ -44,7 +44,7 @@ MessageAttachment::MessageAttachment() { } MessageAttachment::~MessageAttachment() { - LoggerD("MessageAttachment destructor (%p)", this); + ScopeLogger("MessageAttachment destructor (%p)", this); } // id @@ -111,7 +111,7 @@ std::string MessageAttachment::getFilePath() { } std::string MessageAttachment::getShortFileName() const { - LoggerD("Entered"); + ScopeLogger(); if (!m_isFilePathSet) { return ""; } @@ -126,7 +126,7 @@ std::string MessageAttachment::getShortFileName() const { } void MessageAttachment::setFilePath(const std::string& value) { - LoggerD("Entered"); + ScopeLogger(); m_filePath = common::FilesystemProvider::Create().GetRealPath(value); m_isFilePathSet = true; @@ -149,7 +149,7 @@ bool MessageAttachment::isSaved() const { } std::map& MessageAttachment::initializeMIMETypeEnumToStringMap() { - LoggerD("Entered"); + ScopeLogger(); static std::map enumToString; // 0 enumToString[MIME_ASTERISK] = "*/*"; @@ -347,7 +347,7 @@ std::map& MessageAttachment::initializeMIMETypeEnumTo } std::map& MessageAttachment::initializeMIMETypeStringToEnumMap() { - LoggerD("Entered"); + ScopeLogger(); static std::map stringToEnum; // 0 stringToEnum["*/*"] = MIME_ASTERISK; @@ -546,7 +546,7 @@ std::map& MessageAttachment::initializeMIMETypeString } unsigned int MessageAttachment::MIMETypeStringToEnum(std::string str) { - LoggerD("Entered"); + ScopeLogger(); std::map::iterator it = MIMETypeStringToEnumMap.find(str); if (it != MIMETypeStringToEnumMap.end()) { return it->second; @@ -555,7 +555,7 @@ unsigned int MessageAttachment::MIMETypeStringToEnum(std::string str) { } std::string MessageAttachment::MIMETypeEnumToString(unsigned int num) { - LoggerD("Entered"); + ScopeLogger(); std::map::iterator it = MIMETypeEnumToStringMap.find(num); if (it != MIMETypeEnumToStringMap.end()) { return it->second; @@ -564,7 +564,7 @@ std::string MessageAttachment::MIMETypeEnumToString(unsigned int num) { } void MessageAttachment::updateWithAttachmentData(const email_attachment_data_t& attachment_data) { - LoggerD("Entered"); + ScopeLogger(); setId(attachment_data.attachment_id); setMessageId(attachment_data.mail_id); if (attachment_data.attachment_mime_type) { diff --git a/src/messaging/message_body.cc b/src/messaging/message_body.cc index 8349d8e..821acd1 100644 --- a/src/messaging/message_body.cc +++ b/src/messaging/message_body.cc @@ -28,11 +28,11 @@ using namespace common; MessageBody::MessageBody() : m_messageId(1), m_messageId_set(false), m_loaded(false), m_plainBody(""), m_htmlBody("") { - LoggerD("Entered"); + ScopeLogger(); } MessageBody::~MessageBody() { - LoggerD("Entered"); + ScopeLogger(); } // messageId @@ -92,7 +92,7 @@ bool MessageBody::is_message_id_set() const { } PlatformResult MessageBody::updateBody(email_mail_data_t& mail) { - LoggerD("Entered"); + ScopeLogger(); setMessageId(mail.mail_id); setLoaded(mail.body_download_status); diff --git a/src/messaging/message_callback_user_data.cc b/src/messaging/message_callback_user_data.cc index c7479bd..bb6f1b9 100644 --- a/src/messaging/message_callback_user_data.cc +++ b/src/messaging/message_callback_user_data.cc @@ -22,11 +22,11 @@ namespace messaging { MessageCallbackUserData::MessageCallbackUserData(PostQueue& queue, long cid) : CallbackUserData(queue, cid), m_account_id(0) { - LoggerD("Entered"); + ScopeLogger(); } MessageCallbackUserData::~MessageCallbackUserData() { - LoggerD("Entered"); + ScopeLogger(); } void MessageCallbackUserData::setMessage(std::shared_ptr message) { diff --git a/src/messaging/message_conversation.cc b/src/messaging/message_conversation.cc index ed2b475..5d1ea2c 100644 --- a/src/messaging/message_conversation.cc +++ b/src/messaging/message_conversation.cc @@ -40,11 +40,11 @@ MessageConversation::MessageConversation() m_unread_messages(0), m_is_read(false), m_last_message_id(-1) { - LoggerD("Message Conversation constructor."); + ScopeLogger("Message Conversation constructor."); } MessageConversation::~MessageConversation() { - LoggerD("Message Conversation destructor."); + ScopeLogger("Message Conversation destructor."); } // *** attributes getters int MessageConversation::getConversationId() const { @@ -105,7 +105,7 @@ int MessageConversation::getLastMessageId() const { PlatformResult MessageConversation::convertMsgConversationToObject( unsigned int threadId, msg_handle_t handle, std::shared_ptr* result) { - LoggerD("Entered"); + ScopeLogger(); std::shared_ptr conversation(new MessageConversation()); msg_struct_t msgInfo = NULL; @@ -249,7 +249,7 @@ PlatformResult MessageConversation::convertMsgConversationToObject( PlatformResult MessageConversation::convertEmailConversationToObject( unsigned int threadId, std::shared_ptr* result) { - LoggerD("Entered"); + ScopeLogger(); std::shared_ptr conversation(new MessageConversation()); email_mail_list_item_t* resultMail = NULL; @@ -443,7 +443,7 @@ const std::string TO = MESSAGE_CONVERSATION_ATTRIBUTE_TO; bool MessageConversation::isMatchingAttribute(const std::string& attribute_name, const FilterMatchFlag match_flag, AnyPtr match_value) const { - LoggerD("Entered"); + ScopeLogger(); auto key = match_value->toString(); LoggerD("attribute_name: %s match_flag:%d match_value:%s", attribute_name.c_str(), match_flag, key.c_str()); @@ -473,7 +473,7 @@ bool MessageConversation::isMatchingAttribute(const std::string& attribute_name, bool MessageConversation::isMatchingAttributeRange(const std::string& attribute_name, AnyPtr initial_value, AnyPtr end_value) const { - LoggerD("Entered attribute_name: %s", attribute_name.c_str()); + ScopeLogger("attribute_name: " + attribute_name); using namespace CONVERSATION_FILTER_ATTRIBUTE; @@ -486,7 +486,7 @@ bool MessageConversation::isMatchingAttributeRange(const std::string& attribute_ } std::string MessageConversation::SanitizeUtf8String(const std::string& input) { - LoggerD("Entered"); + ScopeLogger(); std::string result = input; const gchar* end = nullptr; diff --git a/src/messaging/message_email.cc b/src/messaging/message_email.cc index d2ee2bf..1ad2f57 100644 --- a/src/messaging/message_email.cc +++ b/src/messaging/message_email.cc @@ -25,24 +25,24 @@ namespace messaging { using namespace common; MessageEmail::MessageEmail() : Message() { - LoggerD("MessageEmail constructor."); + ScopeLogger(); this->m_type = MessageType(EMAIL); } MessageEmail::~MessageEmail() { - LoggerD("MessageEmail destructor."); + ScopeLogger(); } // *** overridden methods int MessageEmail::getFolderIdForUser() const { - LoggerD("Entered"); + ScopeLogger(); // in case of e-mails we're using platform IDs directly return m_folder_id; } void MessageEmail::setCC(std::vector &cc) { - LoggerD("Entered"); + ScopeLogger(); // CC recipient's format validation should be done by email service m_cc = cc; @@ -53,7 +53,7 @@ void MessageEmail::setCC(std::vector &cc) { } void MessageEmail::setBCC(std::vector &bcc) { - LoggerD("Entered"); + ScopeLogger(); // BCC recipient's format validation should be done by email service m_bcc = bcc; @@ -64,17 +64,17 @@ void MessageEmail::setBCC(std::vector &bcc) { } void MessageEmail::setSubject(std::string subject) { - LoggerD("Entered"); + ScopeLogger(); m_subject = subject; } void MessageEmail::setIsHighPriority(bool highpriority) { - LoggerD("Entered"); + ScopeLogger(); m_high_priority = highpriority; } void MessageEmail::setMessageAttachments(AttachmentPtrVector &attachments) { - LoggerD("Entered"); + ScopeLogger(); m_attachments = attachments; m_has_attachment = true; @@ -90,7 +90,7 @@ bool MessageEmail::getHasAttachment() const { } PlatformResult MessageEmail::updateEmailMessage(email_mail_data_t &mail) { - LoggerD("Entered"); + ScopeLogger(); std::vector recp_list; setId(mail.mail_id); diff --git a/src/messaging/message_folder.cc b/src/messaging/message_folder.cc index 87c166d..5a4795a 100644 --- a/src/messaging/message_folder.cc +++ b/src/messaging/message_folder.cc @@ -34,11 +34,11 @@ MessageFolder::MessageFolder(std::string id, std::string parent_id, std::string m_path(path), m_type(type), m_synchronizable(synchronizable) { - LoggerD("Entered"); + ScopeLogger(); } MessageFolder::MessageFolder(email_mailbox_t mailbox) { - LoggerD("Entered"); + ScopeLogger(); m_id = std::to_string(mailbox.mailbox_id); m_parent_id_set = false; m_service_id = std::to_string(mailbox.account_id); @@ -103,7 +103,7 @@ void MessageFolder::setSynchronizable(const bool& value) { } MessageFolderType MessageFolder::convertPlatformFolderType(email_mailbox_type_e folderType) { - LoggerD("Entered"); + ScopeLogger(); switch (folderType) { case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_INBOX: return MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX; @@ -142,7 +142,7 @@ const std::string SERVICE_ID = "serviceId"; bool MessageFolder::isMatchingAttribute(const std::string& attribute_name, const FilterMatchFlag match_flag, AnyPtr match_value) const { - LoggerD("Entered"); + ScopeLogger(); auto key = match_value->toString(); LoggerD("attribute_name: %s match_flag:%d match_value:%s", attribute_name.c_str(), match_flag, key.c_str()); @@ -160,7 +160,7 @@ bool MessageFolder::isMatchingAttribute(const std::string& attribute_name, bool MessageFolder::isMatchingAttributeRange(const std::string& attribute_name, AnyPtr initial_value, AnyPtr end_value) const { - LoggerD("Entered"); + ScopeLogger(); LoggerD("attribute_name: %s NOT SUPPORTED", attribute_name.c_str()); return false; } diff --git a/src/messaging/message_mms.cc b/src/messaging/message_mms.cc index 8ef1cc3..397739b 100644 --- a/src/messaging/message_mms.cc +++ b/src/messaging/message_mms.cc @@ -23,17 +23,17 @@ namespace extension { namespace messaging { MessageMMS::MessageMMS() : Message() { - LoggerD("MessageMMS constructor."); + ScopeLogger(); this->m_type = MessageType(MessageType(MMS)); } MessageMMS::~MessageMMS() { - LoggerD("MessageMMS destructor."); + ScopeLogger(); } // *** overrided methods void MessageMMS::setCC(std::vector &cc) { - LoggerD("Entered"); + ScopeLogger(); // CC recipient's format validation should be done by email service m_cc = cc; @@ -44,7 +44,7 @@ void MessageMMS::setCC(std::vector &cc) { } void MessageMMS::setBCC(std::vector &bcc) { - LoggerD("Entered"); + ScopeLogger(); // BCC recipient's format validation should be done by email service m_bcc = bcc; @@ -59,7 +59,7 @@ void MessageMMS::setSubject(std::string subject) { } void MessageMMS::setMessageAttachments(AttachmentPtrVector &attachments) { - LoggerD("Entered"); + ScopeLogger(); m_attachments = attachments; m_has_attachment = true; @@ -70,7 +70,7 @@ void MessageMMS::setMessageAttachments(AttachmentPtrVector &attachments) { } bool MessageMMS::getHasAttachment() const { - LoggerD("MessageMMS::getHasAttachment()"); + ScopeLogger("MessageMMS::getHasAttachment()"); return m_has_attachment; } diff --git a/src/messaging/message_service.cc b/src/messaging/message_service.cc index 6472985..aa922a5 100644 --- a/src/messaging/message_service.cc +++ b/src/messaging/message_service.cc @@ -46,11 +46,11 @@ MessageRecipientsCallbackData::MessageRecipientsCallbackData(PostQueue& queue, l m_account_id(-1), m_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN), m_default_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN) { - LoggerD("Entered"); + ScopeLogger(); } MessageRecipientsCallbackData::~MessageRecipientsCallbackData() { - LoggerD("Entered"); + ScopeLogger(); } void MessageRecipientsCallbackData::setMessage(std::shared_ptr message) { @@ -79,7 +79,7 @@ int MessageRecipientsCallbackData::getAccountId() const { } bool MessageRecipientsCallbackData::setSimIndex(int sim_index) { - LoggerD("Entered"); + ScopeLogger(); char** cp_list = tel_get_cp_name_list(); int sim_count = 0; if (cp_list) { @@ -124,11 +124,11 @@ TelNetworkDefaultDataSubs_t MessageRecipientsCallbackData::getDefaultSimIndex() BaseMessageServiceCallbackData::BaseMessageServiceCallbackData(PostQueue& queue, long cid) : CallbackUserData(queue, cid), m_op_handle(-1) { - LoggerD("Entered"); + ScopeLogger(); } BaseMessageServiceCallbackData::~BaseMessageServiceCallbackData() { - LoggerD("Entered"); + ScopeLogger(); } void BaseMessageServiceCallbackData::setOperationHandle(const int op_handle) { @@ -142,7 +142,7 @@ int BaseMessageServiceCallbackData::getOperationHandle() const { //#################### MessageBodyCallbackData #################### MessageBodyCallbackData::~MessageBodyCallbackData() { - LoggerD("Entered"); + ScopeLogger(); } void MessageBodyCallbackData::setMessage(std::shared_ptr message) { @@ -157,11 +157,11 @@ std::shared_ptr MessageBodyCallbackData::getMessage() const { MessageAttachmentCallbackData::MessageAttachmentCallbackData(PostQueue& queue, long cid) : BaseMessageServiceCallbackData(queue, cid), m_nth(0) { - LoggerD("Entered"); + ScopeLogger(); } MessageAttachmentCallbackData::~MessageAttachmentCallbackData() { - LoggerD("Entered"); + ScopeLogger(); } void MessageAttachmentCallbackData::setMessageAttachment( @@ -189,11 +189,11 @@ SyncCallbackData::SyncCallbackData(PostQueue& queue, long cid) m_limit(0), m_op_id(-1), m_account_id(-1) { - LoggerD("Entered"); + ScopeLogger(); } SyncCallbackData::~SyncCallbackData() { - LoggerD("Entered"); + ScopeLogger(); } void SyncCallbackData::setLimit(const unsigned long limit) { @@ -228,7 +228,7 @@ int SyncCallbackData::getAccountId() const { //#################### SyncFolderCallbackData #################### SyncFolderCallbackData::~SyncFolderCallbackData() { - LoggerD("Entered"); + ScopeLogger(); } void SyncFolderCallbackData::setMessageFolder(std::shared_ptr message_folder) { @@ -243,7 +243,7 @@ std::shared_ptr SyncFolderCallbackData::getMessageFolder() const MessageService::MessageService(int id, MessageType msgType, const std::string& name) : m_id(id), m_msg_type(msgType), m_name(name) { - LoggerD("Entered"); + ScopeLogger(); switch (msgType) { case MessageType::SMS: case MessageType::MMS: @@ -260,11 +260,11 @@ MessageService::MessageService(int id, MessageType msgType, const std::string& n } MessageService::~MessageService() { - LoggerD("Entered"); + ScopeLogger(); } picojson::object MessageService::toPicoJS() const { - LoggerD("Entered"); + ScopeLogger(); picojson::object picojs = picojson::object(); picojs[JSON_SERVICE_ID] = picojson::value(std::to_string(m_id)); picojs[JSON_SERVICE_TYPE] = picojson::value(getMsgServiceTypeString()); diff --git a/src/messaging/message_service_email.cc b/src/messaging/message_service_email.cc index 6780539..09b941e 100644 --- a/src/messaging/message_service_email.cc +++ b/src/messaging/message_service_email.cc @@ -27,11 +27,11 @@ namespace messaging { MessageServiceEmail::MessageServiceEmail(int id, std::string name) : MessageService(id, MessageType::EMAIL, name) { - LoggerD("Entered"); + ScopeLogger(); } MessageServiceEmail::~MessageServiceEmail() { - LoggerD("Entered"); + ScopeLogger(); for (auto id : registered_callbacks_) { // this may internally fail, because we don't have information about @@ -41,7 +41,7 @@ MessageServiceEmail::~MessageServiceEmail() { } static gboolean sendMessageTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); auto ret = EmailManager::getInstance().sendMessage(static_cast(data)); @@ -54,7 +54,7 @@ static gboolean sendMessageTask(void* data) { } PlatformResult MessageServiceEmail::sendMessage(MessageRecipientsCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); @@ -72,7 +72,7 @@ PlatformResult MessageServiceEmail::sendMessage(MessageRecipientsCallbackData* c } static gboolean loadMessageBodyTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); EmailManager::getInstance().loadMessageBody(static_cast(data)); @@ -80,7 +80,7 @@ static gboolean loadMessageBodyTask(void* data) { } PlatformResult MessageServiceEmail::loadMessageBody(MessageBodyCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); } @@ -95,7 +95,7 @@ PlatformResult MessageServiceEmail::loadMessageBody(MessageBodyCallbackData* cal } static gboolean loadMessageAttachmentTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); auto callback = static_cast(data); @@ -127,7 +127,7 @@ static gboolean loadMessageAttachmentTask(void* data) { } PlatformResult MessageServiceEmail::loadMessageAttachment(MessageAttachmentCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); guint id = g_idle_add(loadMessageAttachmentTask, static_cast(callback)); if (!id) { delete callback; @@ -137,7 +137,7 @@ PlatformResult MessageServiceEmail::loadMessageAttachment(MessageAttachmentCallb } static gboolean syncTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); EmailManager::getInstance().sync(data); @@ -145,7 +145,7 @@ static gboolean syncTask(void* data) { } PlatformResult MessageServiceEmail::sync(SyncCallbackData* callback, long* operation_id) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); @@ -165,7 +165,7 @@ PlatformResult MessageServiceEmail::sync(SyncCallbackData* callback, long* opera } static gboolean syncFolderTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); EmailManager::getInstance().syncFolder(static_cast(data)); @@ -174,7 +174,7 @@ static gboolean syncFolderTask(void* data) { PlatformResult MessageServiceEmail::syncFolder(SyncFolderCallbackData* callback, long* operation_id) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); } @@ -198,7 +198,7 @@ PlatformResult MessageServiceEmail::syncFolder(SyncFolderCallbackData* callback, } static gboolean stopSyncTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); if (!data) { LoggerE("opId is null"); @@ -214,7 +214,7 @@ static gboolean stopSyncTask(void* data) { } PlatformResult MessageServiceEmail::stopSync(long op_id) { - LoggerD("Entered"); + ScopeLogger(); registered_callbacks_.erase(op_id); long* data = new long(op_id); diff --git a/src/messaging/message_service_short_msg.cc b/src/messaging/message_service_short_msg.cc index 290f865..78db705 100644 --- a/src/messaging/message_service_short_msg.cc +++ b/src/messaging/message_service_short_msg.cc @@ -39,15 +39,15 @@ namespace messaging { MessageServiceShortMsg::MessageServiceShortMsg(int id, MessageType msgType) : MessageService(id, msgType, MessagingUtil::messageTypeToString(msgType)) { - LoggerD("Entered"); + ScopeLogger(); } MessageServiceShortMsg::~MessageServiceShortMsg() { - LoggerD("Entered"); + ScopeLogger(); } static gboolean sendMessageThread(void* data) { - LoggerD("Entered"); + ScopeLogger(); auto ret = ShortMsgManager::getInstance().sendMessage(static_cast(data)); @@ -60,7 +60,7 @@ static gboolean sendMessageThread(void* data) { } PlatformResult MessageServiceShortMsg::sendMessage(MessageRecipientsCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); } @@ -118,7 +118,7 @@ PlatformResult MessageServiceShortMsg::sendMessage(MessageRecipientsCallbackData } static gboolean loadMessageBodyTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); MessageBodyCallbackData* callback = static_cast(data); if (!callback) { LoggerE("callback is NULL"); @@ -136,7 +136,7 @@ static gboolean loadMessageBodyTask(void* data) { } PlatformResult MessageServiceShortMsg::loadMessageBody(MessageBodyCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); } @@ -151,11 +151,13 @@ PlatformResult MessageServiceShortMsg::loadMessageBody(MessageBodyCallbackData* } MessageServiceShortMsg* MessageServiceShortMsg::GetMmsMessageService() { + ScopeLogger(); return new (std::nothrow) MessageServiceShortMsg(MessageServiceAccountId::MMS_ACCOUNT_ID, MessageType::MMS); } MessageServiceShortMsg* MessageServiceShortMsg::GetSmsMessageService() { + ScopeLogger(); return new (std::nothrow) MessageServiceShortMsg(MessageServiceAccountId::SMS_ACCOUNT_ID, MessageType::SMS); } diff --git a/src/messaging/message_sms.cc b/src/messaging/message_sms.cc index bf67c8c..32bdcc2 100644 --- a/src/messaging/message_sms.cc +++ b/src/messaging/message_sms.cc @@ -22,12 +22,12 @@ namespace extension { namespace messaging { MessageSMS::MessageSMS() : Message() { - LoggerD("MessageSMS constructor."); + ScopeLogger(); this->m_type = MessageType(MessageType(SMS)); } MessageSMS::~MessageSMS() { - LoggerD("MessageSMS destructor."); + ScopeLogger(); } } // messaging diff --git a/src/messaging/message_storage.cc b/src/messaging/message_storage.cc index 36a771b..b6a5e46 100644 --- a/src/messaging/message_storage.cc +++ b/src/messaging/message_storage.cc @@ -26,11 +26,11 @@ namespace extension { namespace messaging { MessageStorage::MessageStorage(int id, MessageType msgType) : m_id(id), m_msg_type(msgType) { - LoggerD("Entered"); + ScopeLogger(); } MessageStorage::~MessageStorage() { - LoggerD("Entered"); + ScopeLogger(); for (auto id : registered_listeners_) { ChangeListenerContainer::getInstance().removeChangeListener(id); @@ -38,12 +38,12 @@ MessageStorage::~MessageStorage() { } int MessageStorage::getMsgServiceId() const { - LoggerD("Entered"); + ScopeLogger(); return m_id; } MessageType MessageStorage::getMsgServiceType() const { - LoggerD("Entered"); + ScopeLogger(); return m_msg_type; } @@ -52,7 +52,7 @@ std::string MessageStorage::getMsgServiceTypeString() const { } long MessageStorage::addMessagesChangeListener(std::shared_ptr callback) { - LoggerD("Entered"); + ScopeLogger(); long id = ChangeListenerContainer::getInstance().addMessageChangeListener(callback); registered_listeners_.insert(id); return id; @@ -60,21 +60,21 @@ long MessageStorage::addMessagesChangeListener(std::shared_ptr callback) { - LoggerD("Entered"); + ScopeLogger(); long id = ChangeListenerContainer::getInstance().addConversationChangeListener(callback); registered_listeners_.insert(id); return id; } long MessageStorage::addFoldersChangeListener(std::shared_ptr callback) { - LoggerD("Entered"); + ScopeLogger(); long id = ChangeListenerContainer::getInstance().addFolderChangeListener(callback); registered_listeners_.insert(id); return id; } void MessageStorage::removeChangeListener(long watchId) { - LoggerD("Entered"); + ScopeLogger(); ChangeListenerContainer::getInstance().removeChangeListener(watchId); registered_listeners_.erase(watchId); } diff --git a/src/messaging/message_storage_email.cc b/src/messaging/message_storage_email.cc index 432f21b..87e670c 100644 --- a/src/messaging/message_storage_email.cc +++ b/src/messaging/message_storage_email.cc @@ -27,15 +27,15 @@ namespace extension { namespace messaging { MessageStorageEmail::MessageStorageEmail(int id) : MessageStorage(id, MessageType::EMAIL) { - LoggerD("Entered"); + ScopeLogger(); } MessageStorageEmail::~MessageStorageEmail() { - LoggerD("Entered"); + ScopeLogger(); } static gboolean addDraftMessageTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); MessageCallbackUserData* callback = static_cast(data); EmailManager::getInstance().addDraftMessage(callback); @@ -44,7 +44,7 @@ static gboolean addDraftMessageTask(void* data) { } void MessageStorageEmail::addDraftMessage(MessageCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -62,7 +62,7 @@ void MessageStorageEmail::addDraftMessage(MessageCallbackUserData* callback) { } static gboolean removeMessagesTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); MessagesCallbackUserData* callback = static_cast(data); EmailManager::getInstance().removeMessages(callback); @@ -71,7 +71,7 @@ static gboolean removeMessagesTask(void* data) { } void MessageStorageEmail::removeMessages(MessagesCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -89,7 +89,7 @@ void MessageStorageEmail::removeMessages(MessagesCallbackUserData* callback) { } static gboolean updateMessagesTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); MessagesCallbackUserData* callback = static_cast(data); EmailManager::getInstance().updateMessages(callback); @@ -98,7 +98,7 @@ static gboolean updateMessagesTask(void* data) { } void MessageStorageEmail::updateMessages(MessagesCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -115,7 +115,7 @@ void MessageStorageEmail::updateMessages(MessagesCallbackUserData* callback) { } static gboolean findMessagesTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); FindMsgCallbackUserData* callback = static_cast(data); EmailManager::getInstance().findMessages(callback); @@ -124,7 +124,7 @@ static gboolean findMessagesTask(void* data) { } void MessageStorageEmail::findMessages(FindMsgCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -143,7 +143,7 @@ void MessageStorageEmail::findMessages(FindMsgCallbackUserData* callback) { } static gboolean findConversationsTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); ConversationCallbackData* callback = static_cast(data); EmailManager::getInstance().findConversations(callback); @@ -152,7 +152,7 @@ static gboolean findConversationsTask(void* data) { } void MessageStorageEmail::findConversations(ConversationCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -170,7 +170,7 @@ void MessageStorageEmail::findConversations(ConversationCallbackData* callback) } static gboolean removeConversationsTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); ConversationCallbackData* callback = static_cast(data); EmailManager::getInstance().removeConversations(callback); @@ -179,7 +179,7 @@ static gboolean removeConversationsTask(void* data) { } void MessageStorageEmail::removeConversations(ConversationCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -197,7 +197,7 @@ void MessageStorageEmail::removeConversations(ConversationCallbackData* callback } static gboolean findFoldersTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); FoldersCallbackData* callback = static_cast(data); EmailManager::getInstance().findFolders(callback); @@ -206,7 +206,7 @@ static gboolean findFoldersTask(void* data) { } void MessageStorageEmail::findFolders(FoldersCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); diff --git a/src/messaging/message_storage_short_msg.cc b/src/messaging/message_storage_short_msg.cc index 69a1ebd..335b189 100644 --- a/src/messaging/message_storage_short_msg.cc +++ b/src/messaging/message_storage_short_msg.cc @@ -28,15 +28,15 @@ namespace messaging { MessageStorageShortMsg::MessageStorageShortMsg(int id, MessageType msgType) : MessageStorage(id, msgType) { - LoggerD("Entered"); + ScopeLogger(); } MessageStorageShortMsg::~MessageStorageShortMsg() { - LoggerD("Entered"); + ScopeLogger(); } static gboolean addDraftMessageTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); MessageCallbackUserData* callback = static_cast(data); ShortMsgManager::getInstance().addDraftMessage(callback); @@ -45,7 +45,7 @@ static gboolean addDraftMessageTask(void* data) { } void MessageStorageShortMsg::addDraftMessage(MessageCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -61,7 +61,7 @@ void MessageStorageShortMsg::addDraftMessage(MessageCallbackUserData* callback) } static gboolean removeMessagesTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); MessagesCallbackUserData* callback = static_cast(data); ShortMsgManager::getInstance().removeMessages(callback); @@ -70,7 +70,7 @@ static gboolean removeMessagesTask(void* data) { } void MessageStorageShortMsg::removeMessages(MessagesCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -88,7 +88,7 @@ void MessageStorageShortMsg::removeMessages(MessagesCallbackUserData* callback) } static gboolean updateMessagesTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); MessagesCallbackUserData* callback = static_cast(data); ShortMsgManager::getInstance().updateMessages(callback); @@ -97,7 +97,7 @@ static gboolean updateMessagesTask(void* data) { } void MessageStorageShortMsg::updateMessages(MessagesCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -115,7 +115,7 @@ void MessageStorageShortMsg::updateMessages(MessagesCallbackUserData* callback) } static gboolean findMessagesTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); FindMsgCallbackUserData* callback = static_cast(data); ShortMsgManager::getInstance().findMessages(callback); @@ -124,7 +124,7 @@ static gboolean findMessagesTask(void* data) { } void MessageStorageShortMsg::findMessages(FindMsgCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -142,7 +142,7 @@ void MessageStorageShortMsg::findMessages(FindMsgCallbackUserData* callback) { } static gboolean findConversationsTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); ConversationCallbackData* callback = static_cast(data); ShortMsgManager::getInstance().findConversations(callback); @@ -151,7 +151,7 @@ static gboolean findConversationsTask(void* data) { } void MessageStorageShortMsg::findConversations(ConversationCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -169,7 +169,7 @@ void MessageStorageShortMsg::findConversations(ConversationCallbackData* callbac } static gboolean removeConversationsTask(void* data) { - LoggerD("Entered"); + ScopeLogger(); ConversationCallbackData* callback = static_cast(data); ShortMsgManager::getInstance().removeConversations(callback); @@ -178,7 +178,7 @@ static gboolean removeConversationsTask(void* data) { } void MessageStorageShortMsg::removeConversations(ConversationCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -196,7 +196,7 @@ void MessageStorageShortMsg::removeConversations(ConversationCallbackData* callb } static gboolean findFoldersCB(void* data) { - LoggerD("Entered"); + ScopeLogger(); FoldersCallbackData* callback = static_cast(data); @@ -218,7 +218,7 @@ static gboolean findFoldersCB(void* data) { } void MessageStorageShortMsg::findFolders(FoldersCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); return; diff --git a/src/messaging/messages_callback_user_data.cc b/src/messaging/messages_callback_user_data.cc index cb41f5d..ef74d62 100644 --- a/src/messaging/messages_callback_user_data.cc +++ b/src/messaging/messages_callback_user_data.cc @@ -22,15 +22,15 @@ namespace messaging { MessagesCallbackUserData::MessagesCallbackUserData(PostQueue& queue, long cid, bool keep /* = false*/) : CallbackUserData(queue, cid, keep), m_service_type(UNDEFINED) { - LoggerD("Entered"); + ScopeLogger(); } MessagesCallbackUserData::~MessagesCallbackUserData() { - LoggerD("Entered"); + ScopeLogger(); } void MessagesCallbackUserData::addMessage(std::shared_ptr msg) { - LoggerD("Entered"); + ScopeLogger(); m_messages.push_back(msg); } diff --git a/src/messaging/messages_change_callback.cc b/src/messaging/messages_change_callback.cc index 937f942..d262a42 100644 --- a/src/messaging/messages_change_callback.cc +++ b/src/messaging/messages_change_callback.cc @@ -32,7 +32,7 @@ namespace messaging { namespace { std::string limitedString(const std::string& src, const size_t max_len = 40) { - LoggerD("Entered"); + ScopeLogger(); if (src.length() > max_len) { return src.substr(0, max_len); } else { @@ -52,19 +52,19 @@ MessagesChangeCallback::MessagesChangeCallback(long cid, int service_id, Message m_service_id(service_id), m_msg_type(service_type), m_is_act(true) { - LoggerD("Entered"); + ScopeLogger(); m_callback_data.SetListenerId("MessagesChangeListener"); } MessagesChangeCallback::~MessagesChangeCallback() { - LoggerD("Entered"); + ScopeLogger(); } MessagePtrVector MessagesChangeCallback::filterMessages(tizen::AbstractFilterPtr filter, const MessagePtrVector& source_messages, const int service_id) { - LoggerD("Entered sourceMessages.size():%d filter:%s", source_messages.size(), - (filter ? "PRESENT" : "NULL")); + ScopeLogger("sourceMessages.size() = %d filter %s", source_messages.size(), + (filter ? "PRESENT" : "NULL")); if (filter) { MessagePtrVector filtered_messages; @@ -104,7 +104,7 @@ MessagePtrVector MessagesChangeCallback::filterMessages(tizen::AbstractFilterPtr } void MessagesChangeCallback::added(const MessagePtrVector& msgs) { - LoggerD("Entered num messages: %d", msgs.size()); + ScopeLogger("event: msgs.size() = %d", msgs.size()); if (!m_is_act) { return; } @@ -130,7 +130,7 @@ void MessagesChangeCallback::added(const MessagePtrVector& msgs) { } void MessagesChangeCallback::updated(const MessagePtrVector& msgs) { - LoggerD("Entered num messages: %d", msgs.size()); + ScopeLogger("event: msgs.size() = %d", msgs.size()); if (!m_is_act) { return; } @@ -156,7 +156,7 @@ void MessagesChangeCallback::updated(const MessagePtrVector& msgs) { } void MessagesChangeCallback::removed(const MessagePtrVector& msgs) { - LoggerD("Enter event: msgs.size() = %d", msgs.size()); + ScopeLogger("event: msgs.size() = %d", msgs.size()); if (!m_is_act) { return; } diff --git a/src/messaging/messaging_database_manager.cc b/src/messaging/messaging_database_manager.cc index 7e57bc7..4e4edff 100644 --- a/src/messaging/messaging_database_manager.cc +++ b/src/messaging/messaging_database_manager.cc @@ -41,18 +41,18 @@ namespace messaging { AttributeInfo::AttributeInfo() : sql_name(), sql_type(UNDEFINED_TYPE), any_type(PrimitiveType_NoType) { - LoggerD("Entered"); + ScopeLogger(); } AttributeInfo::AttributeInfo(const std::string& in_sql_name, const SQLAttributeType in_sql_type, const tizen::PrimitiveType in_any_type) : sql_name(in_sql_name), sql_type(in_sql_type), any_type(in_any_type) { - LoggerD("Entered"); + ScopeLogger(); } AttributeInfo::AttributeInfo(const AttributeInfo& other) : sql_name(other.sql_name), sql_type(other.sql_type), any_type(other.any_type) { - LoggerD("Entered"); + ScopeLogger(); } AttributeInfo& AttributeInfo::operator=(const AttributeInfo& other) { @@ -63,7 +63,7 @@ AttributeInfo& AttributeInfo::operator=(const AttributeInfo& other) { } MessagingDatabaseManager::MessagingDatabaseManager() { - LoggerD("Entered"); + ScopeLogger(); // Attributes map for short messages ========================================== m_msg_attr_map.insert( std::make_pair("id", AttributeInfo("A.MSG_ID", INTEGER, PrimitiveType_String))); @@ -171,11 +171,11 @@ MessagingDatabaseManager::MessagingDatabaseManager() { } MessagingDatabaseManager::~MessagingDatabaseManager() { - LoggerD("Entered"); + ScopeLogger(); } MessagingDatabaseManager& MessagingDatabaseManager::getInstance() { - LoggerD("Entered"); + ScopeLogger(); static MessagingDatabaseManager instance; return instance; } @@ -184,7 +184,7 @@ __thread sqlite3* sqlHandle = NULL; __thread sqlite3_stmt* stmt = NULL; msg_error_t MessagingDatabaseManager::connect() { - LoggerD("Entered"); + ScopeLogger(); if (NULL == sqlHandle) { char strDBName[64]; @@ -212,7 +212,7 @@ msg_error_t MessagingDatabaseManager::connect() { } msg_error_t MessagingDatabaseManager::disconnect() { - LoggerD("Entered"); + ScopeLogger(); msg_error_t err = 0; if (NULL != sqlHandle) { err = db_util_close(sqlHandle); @@ -231,7 +231,7 @@ msg_error_t MessagingDatabaseManager::disconnect() { msg_error_t MessagingDatabaseManager::getTable(std::string sqlQuery, char*** results, int* resultsCount) { - LoggerD("Entered"); + ScopeLogger(); msg_error_t err = 0; *resultsCount = 0; @@ -261,7 +261,7 @@ msg_error_t MessagingDatabaseManager::getTable(std::string sqlQuery, char*** res } void MessagingDatabaseManager::freeTable(char*** results) { - LoggerD("Entered"); + ScopeLogger(); if (*results) { sqlite3_free_table(*results); *results = NULL; @@ -269,7 +269,7 @@ void MessagingDatabaseManager::freeTable(char*** results) { } int MessagingDatabaseManager::cellToInt(char** array, int cellId) { - LoggerD("Entered"); + ScopeLogger(); if (NULL == array) { LoggerD("Array is NULL"); return 0; @@ -286,7 +286,7 @@ int MessagingDatabaseManager::cellToInt(char** array, int cellId) { std::string MessagingDatabaseManager::getMatchString(tizen::AnyPtr match_value, const PrimitiveType type) const { - LoggerD("Entered"); + ScopeLogger(); if (!match_value) { LoggerD("Warning: match value is NULL"); return std::string(); @@ -344,7 +344,7 @@ PlatformResult MessagingDatabaseManager::getAttributeFilterQuery(AbstractFilterP AttributeInfoMap& attribute_map, MessageType msgType, std::string* result) { - LoggerD("Entered"); + ScopeLogger(); std::ostringstream sqlQuery; AttributeFilterPtr attr_filter = castToAttributeFilter(filter); @@ -548,7 +548,7 @@ PlatformResult MessagingDatabaseManager::getAttributeFilterQuery(AbstractFilterP PlatformResult MessagingDatabaseManager::getAttributeRangeFilterQuery( AbstractFilterPtr filter, AttributeInfoMap& attribute_map, MessageType msg_type, std::string* result) { - LoggerD("Entered"); + ScopeLogger(); std::ostringstream sql_query, converter; std::string initial_value, end_value; @@ -576,7 +576,7 @@ PlatformResult MessagingDatabaseManager::getCompositeFilterQuery(AbstractFilterP AttributeInfoMap& attribute_map, MessageType msg_type, std::string* result) { - LoggerD("Entered"); + ScopeLogger(); std::ostringstream sql_query; CompositeFilterPtr comp_filter = castToCompositeFilter(filter); @@ -652,7 +652,7 @@ PlatformResult MessagingDatabaseManager::addFilters(AbstractFilterPtr filter, So long limit, long offset, AttributeInfoMap& attribute_map, MessageType msg_type, std::string* result) { - LoggerD("Entered"); + ScopeLogger(); std::ostringstream sql_query; // Service type query @@ -743,7 +743,7 @@ PlatformResult MessagingDatabaseManager::addFilters(AbstractFilterPtr filter, So PlatformResult MessagingDatabaseManager::findShortMessages(FindMsgCallbackUserData* callback, std::vector* result) { - LoggerD("Entered"); + ScopeLogger(); std::ostringstream sqlQuery; int attributesCount = 1; // It has to be set manually each time when the query is changed int cellId = attributesCount; @@ -795,7 +795,7 @@ PlatformResult MessagingDatabaseManager::findShortMessages(FindMsgCallbackUserDa PlatformResult MessagingDatabaseManager::findEmails(FindMsgCallbackUserData* callback, std::pair* result) { - LoggerD("Entered"); + ScopeLogger(); std::ostringstream sqlWhereClause; int resultsCount; email_mail_data_t* results; @@ -839,7 +839,7 @@ PlatformResult MessagingDatabaseManager::findEmails(FindMsgCallbackUserData* cal PlatformResult MessagingDatabaseManager::findShortMessageConversations( ConversationCallbackData* callback, std::vector* result) { - LoggerD("Entered"); + ScopeLogger(); std::ostringstream sqlQuery; int attributesCount = 1; // It has to be set manually each time when the query is changed int cellId = attributesCount; @@ -893,7 +893,7 @@ PlatformResult MessagingDatabaseManager::findShortMessageConversations( PlatformResult MessagingDatabaseManager::findEmailConversations( ConversationCallbackData* callback, std::vector* result) { - LoggerD("Entered"); + ScopeLogger(); std::ostringstream sqlWhereClause; int resultsCount; email_mail_data_t* results; diff --git a/src/messaging/messaging_extension.cc b/src/messaging/messaging_extension.cc index 066e5a6..caefca7 100644 --- a/src/messaging/messaging_extension.cc +++ b/src/messaging/messaging_extension.cc @@ -34,7 +34,7 @@ common::Extension* CreateExtension() { } MessagingExtension::MessagingExtension() { - LoggerD("Entered"); + ScopeLogger(); SetExtensionName(kMessaging); SetJavaScriptAPI(kSource_messaging_api); const char* entry_points[] = {kMessage, kMessageAttachment, NULL}; @@ -42,11 +42,11 @@ MessagingExtension::MessagingExtension() { } MessagingExtension::~MessagingExtension() { - LoggerD("Entered"); + ScopeLogger(); } common::Instance* MessagingExtension::CreateInstance() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = extension::messaging::EmailManager::InitializeEmailService(); if (ret.IsError()) { LoggerE("Initializing the email service failed (%s)", ret.message().c_str()); diff --git a/src/messaging/messaging_instance.cc b/src/messaging/messaging_instance.cc index fb0ceec..1446c73 100644 --- a/src/messaging/messaging_instance.cc +++ b/src/messaging/messaging_instance.cc @@ -126,7 +126,7 @@ const long kDumbCallbackId = -1; } MessagingInstance::MessagingInstance() : manager_(*this), queue_(*this) { - LoggerD("Entered"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; #define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&MessagingInstance::x, this, _1, _2)); @@ -158,7 +158,7 @@ MessagingInstance::MessagingInstance() : manager_(*this), queue_(*this) { } MessagingInstance::~MessagingInstance() { - LoggerD("Entered"); + ScopeLogger(); } #define POST_AND_RETURN(ret, json, obj) \ @@ -175,7 +175,7 @@ MessagingInstance::~MessagingInstance() { } void MessagingInstance::GetMessageServices(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -188,7 +188,7 @@ void MessagingInstance::GetMessageServices(const picojson::value& args, picojson void MessagingInstance::MessageServiceSendMessage(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -241,7 +241,7 @@ void MessagingInstance::MessageServiceSendMessage(const picojson::value& args, void MessagingInstance::MessageServiceLoadMessageBody(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -275,7 +275,7 @@ void MessagingInstance::MessageServiceLoadMessageBody(const picojson::value& arg void MessagingInstance::MessageServiceLoadMessageAttachment(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -299,7 +299,7 @@ void MessagingInstance::MessageServiceLoadMessageAttachment(const picojson::valu } void MessagingInstance::MessageServiceSync(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -340,7 +340,7 @@ void MessagingInstance::MessageServiceSync(const picojson::value& args, picojson void MessagingInstance::MessageServiceSyncFolder(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -382,7 +382,7 @@ void MessagingInstance::MessageServiceSyncFolder(const picojson::value& args, } void MessagingInstance::MessageServiceStopSync(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, STOP_SYNC_ARGS_OPID, out); picojson::object data = args.get(); @@ -418,7 +418,7 @@ void MessagingInstance::MessageServiceStopSync(const picojson::value& args, pico } void MessagingInstance::MessageStorageAddDraft(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -450,7 +450,7 @@ void MessagingInstance::MessageStorageAddDraft(const picojson::value& args, pico void MessagingInstance::MessageStorageFindMessages(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -491,7 +491,7 @@ void MessagingInstance::MessageStorageFindMessages(const picojson::value& args, void MessagingInstance::MessageStorageRemoveMessages(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -520,7 +520,7 @@ void MessagingInstance::MessageStorageRemoveMessages(const picojson::value& args void MessagingInstance::MessageStorageUpdateMessages(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -548,7 +548,7 @@ void MessagingInstance::MessageStorageUpdateMessages(const picojson::value& args void MessagingInstance::MessageStorageFindConversations(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -587,7 +587,7 @@ void MessagingInstance::MessageStorageFindConversations(const picojson::value& a void MessagingInstance::MessageStorageRemoveConversations(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingWrite, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -622,7 +622,7 @@ void MessagingInstance::MessageStorageRemoveConversations(const picojson::value& void MessagingInstance::MessageStorageFindFolders(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); CHECK_EXIST(args, JSON_CALLBACK_ID, out); @@ -650,7 +650,7 @@ void MessagingInstance::MessageStorageFindFolders(const picojson::value& args, void MessagingInstance::MessageStorageAddMessagesChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); @@ -680,7 +680,7 @@ void MessagingInstance::MessageStorageAddMessagesChangeListener(const picojson:: void MessagingInstance::MessageStorageAddConversationsChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); @@ -710,7 +710,7 @@ void MessagingInstance::MessageStorageAddConversationsChangeListener(const picoj void MessagingInstance::MessageStorageAddFolderChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); @@ -740,7 +740,7 @@ void MessagingInstance::MessageStorageAddFolderChangeListener(const picojson::va void MessagingInstance::MessageStorageRemoveChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeMessagingRead, &out); @@ -756,7 +756,7 @@ void MessagingInstance::MessageStorageRemoveChangeListener(const picojson::value void MessagingInstance::MessageGetMessageStatus(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); picojson::object data = args.get(); const int id = stoi(data.at("id").get()); diff --git a/src/messaging/messaging_manager.cc b/src/messaging/messaging_manager.cc index e6e9d3b..3016ff9 100644 --- a/src/messaging/messaging_manager.cc +++ b/src/messaging/messaging_manager.cc @@ -52,11 +52,11 @@ MsgManagerCallbackData::MsgManagerCallbackData(MessagingInstance& instance) sms_service(nullptr), mms_service(nullptr), instance_(instance) { - LoggerD("Entered"); + ScopeLogger(); } MessagingManager::MessagingManager(MessagingInstance& instance) : instance_(instance) { - LoggerD("Entered"); + ScopeLogger(); int ret = msg_open_msg_handle(&m_msg_handle); if (ret != MSG_SUCCESS) { LoggerE("Cannot get message handle: %d", ret); @@ -69,7 +69,7 @@ MessagingManager::MessagingManager(MessagingInstance& instance) : instance_(inst } MessagingManager::~MessagingManager() { - LoggerD("Entered"); + ScopeLogger(); int ret = msg_close_msg_handle(&m_msg_handle); if (ret != MSG_SUCCESS) { LoggerW("Cannot close message handle: %d", ret); @@ -88,14 +88,14 @@ MessagingManager::~MessagingManager() { } static gboolean callbackCompleted(const std::shared_ptr& user_data) { - LoggerD("Entered"); + ScopeLogger(); std::shared_ptr response = user_data->json; common::Instance::PostMessage(&user_data->instance_, response->serialize().c_str()); return false; } static void* getMsgServicesThread(const std::shared_ptr& user_data) { - LoggerD("Entered"); + ScopeLogger(); std::shared_ptr response = user_data->json; picojson::object& obj = response->get(); @@ -233,7 +233,7 @@ static void* getMsgServicesThread(const std::shared_ptr& } void MessagingManager::getMessageServices(const std::string& type, double callbackId) { - LoggerD("Entered"); + ScopeLogger(); auto json = std::shared_ptr(new picojson::value(picojson::object())); picojson::object& obj = json->get(); @@ -251,6 +251,7 @@ void MessagingManager::getMessageServices(const std::string& type, double callba } MessageService* MessagingManager::getMessageService(const int id) { + ScopeLogger(); if (id == m_sms_service.first) { return m_sms_service.second; } else if (id == m_mms_service.first) { diff --git a/src/messaging/messaging_util.cc b/src/messaging/messaging_util.cc index 73f50f0..6385c43 100644 --- a/src/messaging/messaging_util.cc +++ b/src/messaging/messaging_util.cc @@ -148,7 +148,7 @@ const std::string FOLDER_TYPE_SENTBOX = "SENTBOX"; } // namespace std::string MessagingUtil::messageFolderTypeToString(MessageFolderType type) { - LoggerD("Entered"); + ScopeLogger(); switch (type) { case MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX: return FOLDER_TYPE_INBOX; @@ -164,7 +164,7 @@ std::string MessagingUtil::messageFolderTypeToString(MessageFolderType type) { } MessageFolderType MessagingUtil::stringToMessageFolderType(std::string type) { - LoggerD("Entered"); + ScopeLogger(); if (FOLDER_TYPE_INBOX == type) { return MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX; } @@ -181,7 +181,7 @@ MessageFolderType MessagingUtil::stringToMessageFolderType(std::string type) { } PlatformResult MessagingUtil::stringToMessageType(const std::string& str, MessageType* out) { - LoggerD("Entered"); + ScopeLogger(); const auto it = stringToTypeMap.find(str); if (it == stringToTypeMap.end()) { @@ -194,7 +194,7 @@ PlatformResult MessagingUtil::stringToMessageType(const std::string& str, Messag } common::PlatformResult MessagingUtil::messageTypeToString(MessageType type, std::string* out) { - LoggerD("Entered"); + ScopeLogger(); const auto it = typeToStringMap.find(type); if (it == typeToStringMap.end()) { @@ -207,7 +207,7 @@ common::PlatformResult MessagingUtil::messageTypeToString(MessageType type, std: } std::string MessagingUtil::messageTypeToString(MessageType type) { - LoggerD("Entered"); + ScopeLogger(); std::string type_str; PlatformResult platform_result = messageTypeToString(type, &type_str); Assert(platform_result); @@ -215,7 +215,7 @@ std::string MessagingUtil::messageTypeToString(MessageType type) { } std::string MessagingUtil::ltrim(const std::string& input) { - LoggerD("Entered"); + ScopeLogger(); std::string str = input; std::string::iterator i; for (i = str.begin(); i != str.end(); ++i) { @@ -232,7 +232,7 @@ std::string MessagingUtil::ltrim(const std::string& input) { } std::string MessagingUtil::extractSingleEmailAddress(const std::string& address) { - LoggerD("Entered"); + ScopeLogger(); std::size_t found_begin = address.rfind('<'); std::size_t found_end = address.rfind('>'); // if both '<' and '>' bracket found and '<' is before '>' @@ -248,7 +248,7 @@ std::string MessagingUtil::extractSingleEmailAddress(const std::string& address) std::vector MessagingUtil::extractEmailAddresses( const std::vector& addresses) { - LoggerD("Entered"); + ScopeLogger(); std::vector extractedAddresses; for (auto it = addresses.begin(); it != addresses.end(); ++it) { extractedAddresses.push_back(MessagingUtil::extractSingleEmailAddress(*it)); @@ -259,7 +259,7 @@ std::vector MessagingUtil::extractEmailAddresses( PlatformResult MessagingUtil::loadFileContentToString(const std::string& file_path, std::string* result) { - LoggerD("Entered"); + ScopeLogger(); std::ifstream input_file; input_file.open(file_path, std::ios::in); @@ -284,14 +284,14 @@ PlatformResult MessagingUtil::loadFileContentToString(const std::string& file_pa namespace { std::string GetFilename(const std::string& file_path) { - LoggerD("Entered"); + ScopeLogger(); const auto start = file_path.find_last_of("/\\"); const auto basename = file_path.substr(std::string::npos == start ? 0 : start + 1); return basename.substr(0, basename.find_last_of(".")); } std::string PerformConversion(const std::string& input, const gchar* from_charset) { - LoggerD("Entered"); + ScopeLogger(); GIConv cd = g_iconv_open("UTF-8//IGNORE", from_charset); @@ -405,7 +405,7 @@ std::string PerformConversion(const std::string& input, const gchar* from_charse std::string MessagingUtil::ConvertToUtf8(const std::string& file_path, const std::string& contents) { - LoggerD("Entered"); + ScopeLogger(); // in case of messages, encoding of the file contents is stored as its filename // is case of draft messages, it is not... @@ -465,7 +465,7 @@ std::string MessagingUtil::ConvertToUtf8(const std::string& file_path, } std::string MessagingUtil::messageStatusToString(MessageStatus status) { - LoggerD("Converting MessageStatus %d to string.", (int)status); + ScopeLogger("Converting MessageStatus %d to string.", (int)status); switch (status) { case STATUS_SENT: return SENT; @@ -485,7 +485,7 @@ std::string MessagingUtil::messageStatusToString(MessageStatus status) { } picojson::value MessagingUtil::messageBodyToJson(std::shared_ptr body) { - LoggerD("Entered"); + ScopeLogger(); picojson::object b; b[MESSAGE_BODY_ATTRIBUTE_MESSAGE_ID] = picojson::value(std::to_string(body->getMessageId())); b[MESSAGE_BODY_ATTRIBUTE_LOADED] = picojson::value(body->getLoaded()); @@ -508,7 +508,7 @@ picojson::value MessagingUtil::messageBodyToJson(std::shared_ptr bo } picojson::value MessagingUtil::messageToJson(std::shared_ptr message) { - LoggerD("Entered"); + ScopeLogger(); picojson::object o; std::vector array; @@ -589,7 +589,7 @@ picojson::value MessagingUtil::messageToJson(std::shared_ptr message) { picojson::value MessagingUtil::conversationToJson( std::shared_ptr conversation) { - LoggerD("Entered"); + ScopeLogger(); picojson::object o; o[MESSAGE_CONVERSATION_ATTRIBUTE_ID] = @@ -654,7 +654,7 @@ picojson::value MessagingUtil::conversationToJson( } picojson::value MessagingUtil::folderToJson(std::shared_ptr folder) { - LoggerD("Entered"); + ScopeLogger(); picojson::object o; @@ -675,7 +675,7 @@ picojson::value MessagingUtil::folderToJson(std::shared_ptr folde PlatformResult MessagingUtil::jsonToMessage(const picojson::value& json, std::shared_ptr* result_message) { - LoggerD("Entered"); + ScopeLogger(); std::shared_ptr message; picojson::object data = json.get(); std::string type = data.at("type").get(); @@ -800,7 +800,7 @@ PlatformResult MessagingUtil::jsonToMessage(const picojson::value& json, } std::shared_ptr MessagingUtil::jsonToMessageBody(const picojson::value& json) { - LoggerD("Entered"); + ScopeLogger(); std::shared_ptr body = std::shared_ptr(new MessageBody()); picojson::object data = json.get(); @@ -837,7 +837,7 @@ std::shared_ptr MessagingUtil::jsonToMessageBody(const picojson::va } std::shared_ptr MessagingUtil::jsonToMessageFolder(const picojson::value& json) { - LoggerD("Entered"); + ScopeLogger(); picojson::object data = json.get(); @@ -879,7 +879,7 @@ std::shared_ptr MessagingUtil::jsonToMessageFolder(const picojson } tizen::SortModePtr MessagingUtil::jsonToSortMode(const picojson::object& json) { - LoggerD("Entered"); + ScopeLogger(); using namespace tizen; const auto it = json.find(JSON_TO_SORT); @@ -897,7 +897,7 @@ tizen::SortModePtr MessagingUtil::jsonToSortMode(const picojson::object& json) { PlatformResult MessagingUtil::jsonToAbstractFilter(const picojson::object& json, tizen::AbstractFilterPtr* result) { - LoggerD("Entered"); + ScopeLogger(); const auto it = json.find(JSON_TO_FILTER); @@ -911,7 +911,7 @@ PlatformResult MessagingUtil::jsonToAbstractFilter(const picojson::object& json, PlatformResult MessagingUtil::jsonFilterToAbstractFilter(const picojson::object& filter, tizen::AbstractFilterPtr* result) { - LoggerD("Entered"); + ScopeLogger(); const auto& type = filter.at(JSON_FILTER_TYPE).get(); if (JSON_FILTER_ATTRIBUTE_TYPE == type) { @@ -930,7 +930,7 @@ PlatformResult MessagingUtil::jsonFilterToAbstractFilter(const picojson::object& PlatformResult MessagingUtil::jsonFilterToAttributeFilter(const picojson::object& filter, tizen::AbstractFilterPtr* result) { - LoggerD("Entered"); + ScopeLogger(); using namespace tizen; @@ -965,7 +965,7 @@ PlatformResult MessagingUtil::jsonFilterToAttributeFilter(const picojson::object PlatformResult MessagingUtil::jsonFilterToAttributeRangeFilter(const picojson::object& filter, tizen::AbstractFilterPtr* result) { - LoggerD("Entered"); + ScopeLogger(); auto name = getValueFromJSONObject(filter, JSON_TO_ATTRIBUTE_NAME); @@ -979,7 +979,7 @@ PlatformResult MessagingUtil::jsonFilterToAttributeRangeFilter(const picojson::o PlatformResult MessagingUtil::jsonFilterToCompositeFilter(const picojson::object& filter, tizen::AbstractFilterPtr* result) { - LoggerD("Entered"); + ScopeLogger(); using namespace tizen; @@ -1016,7 +1016,7 @@ PlatformResult MessagingUtil::jsonFilterToCompositeFilter(const picojson::object std::shared_ptr MessagingUtil::jsonToMessageAttachment( const picojson::value& json) { - LoggerD("Entered"); + ScopeLogger(); picojson::object data = json.get(); int attachmentId = @@ -1039,7 +1039,7 @@ std::shared_ptr MessagingUtil::jsonToMessageAttachment( picojson::value MessagingUtil::messageAttachmentToJson( std::shared_ptr attachment) { - LoggerD("Entered"); + ScopeLogger(); picojson::object o; o[MESSAGE_ATTACHMENT_ATTRIBUTE_ID] = attachment->isIdSet() @@ -1061,7 +1061,7 @@ picojson::value MessagingUtil::messageAttachmentToJson( PlatformResult MessagingUtil::jsonToMessageConversation( const picojson::value& json, std::shared_ptr* result_conversation) { - LoggerD("Entered"); + ScopeLogger(); std::shared_ptr conversation; picojson::object data = json.get(); std::string type = data.at("type").get(); @@ -1138,16 +1138,16 @@ PlatformResult MessagingUtil::jsonToMessageConversation( } PostQueue::PostQueue(MessagingInstance& instance) : instance_(instance) { - LoggerD("Entered: [%p]", this); + ScopeLogger("this: [%p]", this); } PostQueue::~PostQueue() { - LoggerD("Entered: [%p]", this); + ScopeLogger("this: [%p]", this); EmailManager::getInstance().RemoveCallbacksByQueue(*this); } void PostQueue::addAndResolve(const long cid, PostPriority priority, const std::string& json) { - LoggerD("Entered"); + ScopeLogger(); std::shared_ptr t(new PostTask(priority)); t->attach(json); @@ -1161,7 +1161,7 @@ void PostQueue::addAndResolve(const long cid, PostPriority priority, const std:: } void PostQueue::add(const long cid, PostPriority priority) { - LoggerD("Entered"); + ScopeLogger(); tasks_mutex_.lock(); tasks_.push_back(std::make_pair(cid, std::shared_ptr(new PostTask(priority)))); @@ -1171,7 +1171,7 @@ void PostQueue::add(const long cid, PostPriority priority) { } void PostQueue::resolve(const long cid, const std::string& json) { - LoggerD("Entered: [%p]", this); + ScopeLogger("this: [%p]", this); tasks_mutex_.lock(); @@ -1193,7 +1193,7 @@ void PostQueue::resolve(const long cid, const std::string& json) { } void PostQueue::resolve(PostPriority p) { - LoggerD("Entered: [%p]", this); + ScopeLogger("this: [%p]", this); TasksCollection::iterator i; @@ -1234,21 +1234,21 @@ void PostQueue::resolve(PostPriority p) { } PostQueue::PostTask::PostTask() { - LoggerD("Entered"); + ScopeLogger(); priority_ = PostPriority::LOW; state_ = TaskState::NEW; } PostQueue::PostTask::PostTask(PostPriority p) { - LoggerD("Entered"); + ScopeLogger(); priority_ = p; state_ = TaskState::NEW; } PostQueue::PostTask::~PostTask() { - LoggerD("Entered"); + ScopeLogger(); } void PostQueue::PostTask::attach(const std::string& j) { - LoggerD("Entered"); + ScopeLogger(); if (TaskState::DONE == state_) { return; } @@ -1270,7 +1270,7 @@ std::string PostQueue::PostTask::json() { } void PostQueue::PostTask::resolve() { - LoggerD("Entered"); + ScopeLogger(); if (TaskState::READY == state_) { state_ = TaskState::DONE; } diff --git a/src/messaging/short_message_manager.cc b/src/messaging/short_message_manager.cc index 238d697..8bc5468 100644 --- a/src/messaging/short_message_manager.cc +++ b/src/messaging/short_message_manager.cc @@ -40,14 +40,14 @@ namespace extension { namespace messaging { ShortMsgManager& ShortMsgManager::getInstance() { - LoggerD("Entered"); + ScopeLogger(); static ShortMsgManager instance; return instance; } static gboolean sendMessageCompleteCB(void* data) { - LoggerD("Entered callback:%p", data); + ScopeLogger("callback:%p", data); MessageRecipientsCallbackData* callback = static_cast(data); if (!callback) { @@ -87,7 +87,7 @@ static gboolean sendMessageCompleteCB(void* data) { } static gboolean addDraftMessageCompleteCB(void* data) { - LoggerD("Enter"); + ScopeLogger(); auto callback = static_cast(data); if (!callback) { LoggerE("Callback is null"); @@ -116,7 +116,7 @@ static gboolean addDraftMessageCompleteCB(void* data) { } PlatformResult ShortMsgManager::addDraftMessagePlatform(std::shared_ptr message) { - LoggerD("Add new message(%p)", message.get()); + ScopeLogger("Add new message(%p)", message.get()); // Save platform msg to get ID msg_struct_t platform_msg = nullptr; @@ -191,7 +191,7 @@ PlatformResult ShortMsgManager::addDraftMessagePlatform(std::shared_ptr } PlatformResult ShortMsgManager::SendMessagePlatform(MessageRecipientsCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(m_mutex); PlatformResult platform_result(ErrorCode::NO_ERROR); @@ -320,7 +320,7 @@ PlatformResult ShortMsgManager::SendMessagePlatform(MessageRecipientsCallbackDat } PlatformResult ShortMsgManager::sendMessage(MessageRecipientsCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); @@ -345,7 +345,7 @@ PlatformResult ShortMsgManager::sendMessage(MessageRecipientsCallbackData* callb } void ShortMsgManager::sendStatusCallback(msg_struct_t sent_status) { - LoggerD("Entered"); + ScopeLogger(); int reqId = 0; int status = MSG_NETWORK_NOT_SEND; @@ -389,7 +389,7 @@ void ShortMsgManager::sendStatusCallback(msg_struct_t sent_status) { } static void sent_status_cb(msg_handle_t handle, msg_struct_t sent_status, void* data) { - LoggerD("Entered"); + ScopeLogger(); ShortMsgManager::getInstance().sendStatusCallback(sent_status); return; @@ -397,8 +397,8 @@ static void sent_status_cb(msg_handle_t handle, msg_struct_t sent_status, void* PlatformResult ShortMsgManager::callProperEventMessages( EventMessages* event, msg_storage_change_type_t storageChangeType) { - LoggerD( - "Entered event.items.size()=%d event.removed_conversations.size()=%d" + ScopeLogger( + "event.items.size()=%d event.removed_conversations.size()=%d" " sChangeType:%d", event->items.size(), event->removed_conversations.size(), storageChangeType); @@ -481,8 +481,7 @@ PlatformResult ShortMsgManager::callProperEventMessages( void ShortMsgManager::storage_change_cb(msg_handle_t handle, msg_storage_change_type_t storageChangeType, msg_id_list_s* pMsgIdList, void* data) { - LoggerD("Entered handle:%p sChangeType:%d numMsgs:%d", handle, storageChangeType, - pMsgIdList->nCount); + ScopeLogger("handle:%p sChangeType:%d numMsgs:%d", handle, storageChangeType, pMsgIdList->nCount); if (MSG_STORAGE_CHANGE_CONTACT == storageChangeType) { LoggerD("storageChangeType is MSG_STORAGE_CHANGE_CONTACT, ignoring"); @@ -651,7 +650,7 @@ void ShortMsgManager::storage_change_cb(msg_handle_t handle, } void ShortMsgManager::registerStatusCallback(msg_handle_t msg_handle) { - LoggerD("Entered"); + ScopeLogger(); m_msg_handle = msg_handle; // set message sent status callback if (MSG_SUCCESS != msg_reg_sent_status_callback(m_msg_handle, &sent_status_cb, NULL)) { @@ -663,7 +662,7 @@ void ShortMsgManager::registerStatusCallback(msg_handle_t msg_handle) { } void ShortMsgManager::addDraftMessage(MessageCallbackUserData* callback) { - LoggerD("Enter"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -689,7 +688,7 @@ void ShortMsgManager::addDraftMessage(MessageCallbackUserData* callback) { } void ShortMsgManager::removeMessages(MessagesCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -754,7 +753,7 @@ void ShortMsgManager::removeMessages(MessagesCallbackUserData* callback) { } void ShortMsgManager::updateMessages(MessagesCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -829,7 +828,7 @@ void ShortMsgManager::updateMessages(MessagesCallbackUserData* callback) { } PlatformResult ShortMsgManager::getMessage(int msg_id, msg_struct_t* out_msg) { - LoggerD("Entered"); + ScopeLogger(); msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT); msg_struct_t msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO); @@ -849,7 +848,7 @@ PlatformResult ShortMsgManager::getMessage(int msg_id, msg_struct_t* out_msg) { PlatformResult ShortMsgManager::getConversationsForMessages( MessagePtrVector messages, msg_storage_change_type_t storageChangeType, ConversationPtrVector* result) { - LoggerD("Entered messages.size()=%d storageChangeType=%d", messages.size(), storageChangeType); + ScopeLogger("messages.size()=%d storageChangeType=%d", messages.size(), storageChangeType); std::unordered_set unique_conv_ids; ConversationPtrVector convs; @@ -879,7 +878,7 @@ PlatformResult ShortMsgManager::getConversationsForMessages( } void ShortMsgManager::findMessages(FindMsgCallbackUserData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -959,7 +958,7 @@ void ShortMsgManager::findMessages(FindMsgCallbackUserData* callback) { } void ShortMsgManager::findConversations(ConversationCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -1015,7 +1014,7 @@ void ShortMsgManager::findConversations(ConversationCallbackData* callback) { } void ShortMsgManager::removeConversations(ConversationCallbackData* callback) { - LoggerD("Entered"); + ScopeLogger(); if (!callback) { LoggerE("Callback is null"); @@ -1133,11 +1132,11 @@ void ShortMsgManager::removeConversations(ConversationCallbackData* callback) { } ShortMsgManager::ShortMsgManager() : m_msg_handle(NULL) { - LoggerD("Entered"); + ScopeLogger(); } ShortMsgManager::~ShortMsgManager() { - LoggerD("Entered"); + ScopeLogger(); LoggerD("m_sms_removed_messages.size() = %d", m_sms_removed_messages.size()); LoggerD("m_mms_removed_messages.size() = %d", m_mms_removed_messages.size()); LoggerD("m_sms_removed_msg_id_conv_id_map.size() = %d", m_sms_removed_msg_id_conv_id_map.size()); @@ -1146,7 +1145,7 @@ ShortMsgManager::~ShortMsgManager() { LoggerD("m_mms_removed_conv_id_object_map.size() = %d", m_mms_removed_conv_id_object_map.size()); } std::string ShortMsgManager::getMessageStatus(int id) { - LoggerD("Entered"); + ScopeLogger(); msg_struct_t send_opt = nullptr; msg_struct_t msg = nullptr; diff --git a/src/networkbearerselection/networkbearerselection_instance.cc b/src/networkbearerselection/networkbearerselection_instance.cc index 65a89d2..ea33972 100644 --- a/src/networkbearerselection/networkbearerselection_instance.cc +++ b/src/networkbearerselection/networkbearerselection_instance.cc @@ -41,7 +41,7 @@ using namespace common; using namespace extension::networkbearerselection; NetworkBearerSelectionInstance::NetworkBearerSelectionInstance() { - LoggerD("Entered"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -60,7 +60,7 @@ NetworkBearerSelectionInstance::NetworkBearerSelectionInstance() { } NetworkBearerSelectionInstance::~NetworkBearerSelectionInstance() { - LoggerD("Entered"); + ScopeLogger(); NetworkBearerSelectionManager::GetInstance()->RemoveListener(this); } @@ -72,7 +72,7 @@ NetworkBearerSelectionInstance::~NetworkBearerSelectionInstance() { void NetworkBearerSelectionInstance::NetworkBearerSelectionRequestRouteToHost( const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kNbsPrivileges, &out); @@ -90,7 +90,7 @@ void NetworkBearerSelectionInstance::NetworkBearerSelectionRequestRouteToHost( auto request = [=]() -> void { auto response = [this, domain_name, id](const common::PlatformResult result) -> void { - LoggerD("Entered"); + ScopeLogger(); picojson::value value{picojson::object{}}; picojson::object& obj = value.get(); @@ -116,7 +116,7 @@ void NetworkBearerSelectionInstance::NetworkBearerSelectionRequestRouteToHost( void NetworkBearerSelectionInstance::NetworkBearerSelectionReleaseRouteToHost( const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kNbsPrivileges, &out); @@ -136,7 +136,7 @@ void NetworkBearerSelectionInstance::NetworkBearerSelectionReleaseRouteToHost( auto release = [=]() -> void { auto response = [this, domain_name, id](const common::PlatformResult result) -> void { - LoggerD("Entered"); + ScopeLogger(); picojson::value value{picojson::object{}}; picojson::object& obj = value.get(); @@ -160,7 +160,7 @@ void NetworkBearerSelectionInstance::NetworkBearerSelectionReleaseRouteToHost( } void NetworkBearerSelectionInstance::onNBSEvent(const std::string& status) { - LoggerD("Entered"); + ScopeLogger(); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); @@ -179,14 +179,14 @@ void NetworkBearerSelectionInstance::onNBSEvent(const std::string& status) { void NetworkBearerSelectionInstance::addDomainListener(const std::string& domain_name, int listener_id) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(m_listener_mutex_); listenerMap.insert(std::make_pair(domain_name, listener_id)); } void NetworkBearerSelectionInstance::removeDomainListener(const std::string& domain_name) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(m_listener_mutex_); listenerMap.erase(domain_name); diff --git a/src/networkbearerselection/networkbearerselection_manager.cc b/src/networkbearerselection/networkbearerselection_manager.cc index 37ecdc1..b6206f4 100644 --- a/src/networkbearerselection/networkbearerselection_manager.cc +++ b/src/networkbearerselection/networkbearerselection_manager.cc @@ -39,25 +39,26 @@ struct NetworkBearerSelectionEvent { NetworkBearerSelectionEvent(const std::string& dm, const ReplyCallback& cb) : domain_name(dm), callback(cb) { + ScopeLogger(); } }; void NetworkBearerSelectionManager::AddListener(NetworkBearerSelectionInstance* listener) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(m_mutex_); m_listeners_.push_back(listener); } void NetworkBearerSelectionManager::RemoveListener(NetworkBearerSelectionInstance* listener) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(m_mutex_); m_listeners_.remove(listener); } NetworkBearerSelectionManager* NetworkBearerSelectionManager::GetInstance() { - LoggerD("Entered"); + ScopeLogger(); static NetworkBearerSelectionManager instance; return &instance; @@ -68,7 +69,7 @@ NetworkBearerSelectionManager::NetworkBearerSelectionManager() m_profile_handle_(nullptr), m_profile_name_(), m_is_connection_opened_(false) { - LoggerD("Entered"); + ScopeLogger(); int ret = connection_create(&m_connection_handle_); if (CONNECTION_ERROR_NONE == ret) { @@ -80,7 +81,7 @@ NetworkBearerSelectionManager::NetworkBearerSelectionManager() } NetworkBearerSelectionManager::~NetworkBearerSelectionManager() { - LoggerD("Entered"); + ScopeLogger(); for (auto it = m_domain_names_.begin(); it != m_domain_names_.end(); ++it) { if (!removeDomainRoute(it)) { @@ -98,7 +99,7 @@ NetworkBearerSelectionManager::~NetworkBearerSelectionManager() { void NetworkBearerSelectionManager::connection_state_changed_callback( connection_profile_state_e state, void* user_data) { - LoggerD("Entered [%d]", state); + ScopeLogger("state: %d", state); if (CONNECTION_PROFILE_STATE_CONNECTED == state) { NetworkBearerSelectionManager::GetInstance()->makeSuccessCallback(); @@ -109,7 +110,7 @@ void NetworkBearerSelectionManager::connection_state_changed_callback( void NetworkBearerSelectionManager::connection_opened_callback(connection_error_e result, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); NetworkBearerSelectionEvent* event = static_cast(user_data); if (!event) { LoggerE("Event not found"); @@ -135,7 +136,7 @@ void NetworkBearerSelectionManager::connection_opened_callback(connection_error_ void NetworkBearerSelectionManager::connection_closed_callback(connection_error_e result, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); NetworkBearerSelectionEvent* event = static_cast(user_data); if (!event) { LoggerE("Event not found"); @@ -160,7 +161,7 @@ void NetworkBearerSelectionManager::connection_closed_callback(connection_error_ } PlatformResult NetworkBearerSelectionManager::getCellularState() { - LoggerD("Entered"); + ScopeLogger(); connection_cellular_state_e state; @@ -180,14 +181,14 @@ PlatformResult NetworkBearerSelectionManager::getCellularState() { void NetworkBearerSelectionManager::callResultCallback(const ReplyCallback& reply, const PlatformResult result) { - LoggerD("Entered"); + ScopeLogger(); std::thread(reply, result).detach(); } void NetworkBearerSelectionManager::requestRouteToHost(const std::string& domain_name, const ReplyCallback& reply) { - LoggerD("Entered"); + ScopeLogger(); connection_profile_h profile_h = nullptr; char* current_profile_name_c = nullptr; @@ -259,7 +260,7 @@ void NetworkBearerSelectionManager::requestRouteToHost(const std::string& domain bool NetworkBearerSelectionManager::removeDomainRoute( const std::map::iterator& iter) { - LoggerD("Entered"); + ScopeLogger(); const char* domain_name = iter->first.c_str(); char* interface_name = nullptr; @@ -306,7 +307,7 @@ bool NetworkBearerSelectionManager::removeDomainRoute( void NetworkBearerSelectionManager::releaseRouteToHost(const std::string& domain_name, const ReplyCallback& reply) { - LoggerD("Entered"); + ScopeLogger(); if (!m_profile_handle_) { callResultCallback(reply, @@ -345,7 +346,7 @@ void NetworkBearerSelectionManager::releaseRouteToHost(const std::string& domain } bool NetworkBearerSelectionManager::registerStateChangeListener(const std::string& domain_name) { - LoggerD("Entered"); + ScopeLogger(); char* interface_name = nullptr; char* gateway = nullptr; @@ -435,7 +436,7 @@ bool NetworkBearerSelectionManager::registerStateChangeListener(const std::strin } bool NetworkBearerSelectionManager::deregisterStateChangeListener(const std::string& domain_name) { - LoggerD("Entered"); + ScopeLogger(); if (m_profile_handle_) { int ret = connection_profile_unset_state_changed_cb(m_profile_handle_); @@ -450,7 +451,7 @@ bool NetworkBearerSelectionManager::deregisterStateChangeListener(const std::str } void NetworkBearerSelectionManager::makeSuccessCallback() { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(m_mutex_); for (NetworkBearerSelectionInstance* listener : m_listeners_) { @@ -459,7 +460,7 @@ void NetworkBearerSelectionManager::makeSuccessCallback() { } void NetworkBearerSelectionManager::makeDisconnectCallback() { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(m_mutex_); for (NetworkBearerSelectionInstance* listener : m_listeners_) { @@ -468,7 +469,7 @@ void NetworkBearerSelectionManager::makeDisconnectCallback() { } void NetworkBearerSelectionManager::destroyProfileHandler() { - LoggerD("Entered"); + ScopeLogger(); if (m_profile_handle_) { if (CONNECTION_ERROR_NONE != connection_profile_destroy(m_profile_handle_)) { @@ -478,7 +479,7 @@ void NetworkBearerSelectionManager::destroyProfileHandler() { } ErrorCode NetworkBearerSelectionManager::GetNBSErrorCode(int error_code) { - LoggerD("Entered"); + ScopeLogger(); switch (error_code) { case CONNECTION_ERROR_NOT_SUPPORTED: @@ -489,7 +490,7 @@ ErrorCode NetworkBearerSelectionManager::GetNBSErrorCode(int error_code) { } bool NetworkBearerSelectionManager::createProfileHandler() { - LoggerD("Entered"); + ScopeLogger(); if (!m_connection_handle_) { LoggerE("Connection handle is not created"); diff --git a/src/nfc/aid_data.cc b/src/nfc/aid_data.cc index 239871f..0acd282 100644 --- a/src/nfc/aid_data.cc +++ b/src/nfc/aid_data.cc @@ -23,11 +23,11 @@ namespace nfc { AIDData::AIDData(std::string se_type, std::string aid, bool read_only) : se_type_(se_type), aid_(aid), read_only_(read_only) { - LoggerD("Entered"); + ScopeLogger(); } picojson::value AIDData::toJSON() const { - LoggerD("Entered"); + ScopeLogger(); picojson::value retval = picojson::value(picojson::object()); picojson::object& obj = retval.get(); diff --git a/src/nfc/nfc_adapter.cc b/src/nfc/nfc_adapter.cc index 8c3b5ca..d29aa70 100644 --- a/src/nfc/nfc_adapter.cc +++ b/src/nfc/nfc_adapter.cc @@ -54,7 +54,7 @@ const std::string HCE_EVENT_LISTENER = "HCEEventListener"; void HCEEventCallback(nfc_se_h handle, nfc_hce_event_type_e event_type, unsigned char* apdu, unsigned int apdu_len, void* /*user_data*/) { - LoggerD("Entered"); + ScopeLogger(); NFCAdapter::GetInstance()->SetSEHandle(handle); picojson::value response = picojson::value(picojson::object()); @@ -90,7 +90,7 @@ NFCAdapter::NFCAdapter() m_se_handle(nullptr), m_is_hce_listener_set(false), responder_(nullptr) { - LoggerD("Entered"); + ScopeLogger(); // NFC library initialization int ret = nfc_manager_initialize(); if (ret != NFC_ERROR_NONE) { @@ -99,7 +99,7 @@ NFCAdapter::NFCAdapter() } NFCAdapter::~NFCAdapter() { - LoggerD("Entered"); + ScopeLogger(); if (m_is_listener_set) { nfc_manager_unset_se_event_cb(); } @@ -130,12 +130,12 @@ NFCAdapter::~NFCAdapter() { } void NFCAdapter::SetResponder(IResponder* responder) { - LoggerD("Entered"); + ScopeLogger(); responder_ = responder; } void NFCAdapter::RespondAsync(const char* msg) { - LoggerD("Entered"); + ScopeLogger(); if (GetInstance()->responder_) { AssertMsg(GetInstance()->responder_, "Handler variable should be set"); GetInstance()->responder_->RespondAsync(msg); @@ -145,7 +145,7 @@ void NFCAdapter::RespondAsync(const char* msg) { } static picojson::value CreateEventError(double callbackId, const PlatformResult& ret) { - LoggerD("Entered"); + ScopeLogger(); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); @@ -156,7 +156,7 @@ static picojson::value CreateEventError(double callbackId, const PlatformResult& } static picojson::value createEventSuccess(double callbackId) { - LoggerD("Entered"); + ScopeLogger(); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); tools::ReportSuccess(obj); @@ -166,7 +166,7 @@ static picojson::value createEventSuccess(double callbackId) { } static gboolean setPoweredCompleteCB(void* user_data) { - LoggerD("Entered"); + ScopeLogger(); double* callbackId = static_cast(user_data); picojson::value event = createEventSuccess(*callbackId); NFCAdapter::GetInstance()->RespondAsync(event.serialize().c_str()); @@ -178,7 +178,7 @@ static gboolean setPoweredCompleteCB(void* user_data) { static void targetDetectedCallback(nfc_discovered_type_e type, nfc_p2p_target_h target, void* /*user_data*/) { - LoggerD("Entered"); + ScopeLogger(); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); obj[JSON_LISTENER_ID] = picojson::value(PEER_LISTENER); @@ -203,20 +203,20 @@ static void targetDetectedCallback(nfc_discovered_type_e type, nfc_p2p_target_h } NFCAdapter* NFCAdapter::GetInstance() { - LoggerD("Entered"); + ScopeLogger(); static NFCAdapter instance; return &instance; } bool NFCAdapter::GetPowered() { - LoggerD("Entered"); + ScopeLogger(); return nfc_manager_is_activated(); } #ifndef APP_CONTROL_SETTINGS_SUPPORT static void NFCSetActivationCompletedCallback(nfc_error_e error, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); double* callbackId = static_cast(user_data); if (NFC_ERROR_NONE != error) { @@ -237,7 +237,7 @@ static void NFCSetActivationCompletedCallback(nfc_error_e error, void* user_data #endif static void se_event_callback(nfc_se_event_e se_event, void* /*user_data*/) { - LoggerD("Entered"); + ScopeLogger(); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); tools::ReportSuccess(obj); @@ -265,7 +265,7 @@ static void se_event_callback(nfc_se_event_e se_event, void* /*user_data*/) { static void transaction_event_callback(nfc_se_type_e type, unsigned char* _aid, int aid_size, unsigned char* param, int param_size, void* /*user_data*/) { - LoggerD("Entered"); + ScopeLogger(); picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); tools::ReportSuccess(response_obj); @@ -298,6 +298,7 @@ static void transaction_event_callback(nfc_se_type_e type, unsigned char* _aid, #ifdef APP_CONTROL_SETTINGS_SUPPORT static void PostMessage(double* callbackId) { + ScopeLogger(); LoggerE("Posting error message."); picojson::value event = CreateEventError(*callbackId, PlatformResult(ErrorCode::UNKNOWN_ERR, "SetPowered failed.")); @@ -308,7 +309,7 @@ static void PostMessage(double* callbackId) { #endif PlatformResult NFCAdapter::SetPowered(const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); double* callbackId = new double(args.get(JSON_CALLBACK_ID).get()); bool powered = args.get("powered").get(); @@ -358,6 +359,8 @@ PlatformResult NFCAdapter::SetPowered(const picojson::value& args) { ret = app_control_send_launch_request( service, [](app_control_h request, app_control_h reply, app_control_result_e result, void* user_data) { + ScopeLogger( + "Entered into asynchronous function, app_control_send_launch_request's argument"); double* callbackId = static_cast(user_data); if (result != APP_CONTROL_RESULT_SUCCEEDED) { LoggerE("NFC enable app control failed : %d", result); @@ -403,7 +406,7 @@ PlatformResult NFCAdapter::SetPowered(const picojson::value& args) { } PlatformResult NFCAdapter::GetCardEmulationMode(std::string* mode) { - LoggerD("Entered"); + ScopeLogger(); nfc_se_card_emulation_mode_type_e card_mode; int ret = nfc_se_get_card_emulation_mode(&card_mode); @@ -417,7 +420,7 @@ PlatformResult NFCAdapter::GetCardEmulationMode(std::string* mode) { } PlatformResult NFCAdapter::SetCardEmulationMode(const std::string& mode) { - LoggerD("Entered"); + ScopeLogger(); nfc_se_card_emulation_mode_type_e new_mode; PlatformResult result = NFCUtil::ToCardEmulationMode(mode, &new_mode); @@ -462,7 +465,7 @@ PlatformResult NFCAdapter::SetCardEmulationMode(const std::string& mode) { } PlatformResult NFCAdapter::GetActiveSecureElement(std::string* type) { - LoggerD("Entered"); + ScopeLogger(); nfc_se_type_e se_type = NFC_SE_TYPE_DISABLE; int ret = nfc_manager_get_se_type(&se_type); @@ -475,7 +478,7 @@ PlatformResult NFCAdapter::GetActiveSecureElement(std::string* type) { } PlatformResult NFCAdapter::SetActiveSecureElement(std::string element) { - LoggerD("Entered"); + ScopeLogger(); // if given value is not correct secure element type then // there's no sense to get current value for comparison @@ -510,7 +513,7 @@ PlatformResult NFCAdapter::SetActiveSecureElement(std::string element) { } PlatformResult NFCAdapter::SetExclusiveModeForTransaction(bool exmode) { - LoggerD("Entered"); + ScopeLogger(); int ret = NFC_ERROR_NONE; if (exmode) { @@ -527,7 +530,7 @@ PlatformResult NFCAdapter::SetExclusiveModeForTransaction(bool exmode) { } PlatformResult NFCAdapter::AddCardEmulationModeChangeListener() { - LoggerD("Entered"); + ScopeLogger(); if (!m_is_listener_set) { int ret = nfc_manager_set_se_event_cb(se_event_callback, nullptr); if (NFC_ERROR_NONE != ret) { @@ -541,7 +544,7 @@ PlatformResult NFCAdapter::AddCardEmulationModeChangeListener() { } PlatformResult NFCAdapter::RemoveCardEmulationModeChangeListener() { - LoggerD("Entered"); + ScopeLogger(); if (!nfc_manager_is_supported()) { return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NFC Not Supported"); } @@ -554,7 +557,7 @@ PlatformResult NFCAdapter::RemoveCardEmulationModeChangeListener() { } PlatformResult NFCAdapter::AddTransactionEventListener(const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); nfc_se_type_e se_type = NFC_SE_TYPE_DISABLE; PlatformResult result = NFCUtil::ToSecureElementType(args.get(JSON_TYPE).get(), &se_type); @@ -589,7 +592,7 @@ PlatformResult NFCAdapter::AddTransactionEventListener(const picojson::value& ar } PlatformResult NFCAdapter::RemoveTransactionEventListener(const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); nfc_se_type_e se_type = NFC_SE_TYPE_DISABLE; PlatformResult result = NFCUtil::ToSecureElementType(args.get(JSON_TYPE).get(), &se_type); @@ -613,7 +616,7 @@ PlatformResult NFCAdapter::RemoveTransactionEventListener(const picojson::value& } PlatformResult NFCAdapter::AddActiveSecureElementChangeListener() { - LoggerD("Entered"); + ScopeLogger(); if (!m_is_listener_set) { int ret = nfc_manager_set_se_event_cb(se_event_callback, nullptr); if (NFC_ERROR_NONE != ret) { @@ -627,7 +630,7 @@ PlatformResult NFCAdapter::AddActiveSecureElementChangeListener() { } PlatformResult NFCAdapter::RemoveActiveSecureElementChangeListener() { - LoggerD("Entered"); + ScopeLogger(); if (!nfc_manager_is_supported()) { return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NFC Not Supported"); } @@ -640,27 +643,27 @@ PlatformResult NFCAdapter::RemoveActiveSecureElementChangeListener() { } void NFCAdapter::SetPeerHandle(nfc_p2p_target_h handle) { - LoggerD("Entered"); + ScopeLogger(); m_peer_handle = handle; } nfc_p2p_target_h NFCAdapter::GetPeerHandle() { - LoggerD("Entered"); + ScopeLogger(); return m_peer_handle; } int NFCAdapter::GetPeerId() { - LoggerD("Entered"); + ScopeLogger(); return m_latest_peer_id; } void NFCAdapter::IncreasePeerId() { - LoggerD("Entered"); + ScopeLogger(); m_latest_peer_id++; } PlatformResult NFCAdapter::PeerIsConnectedGetter(int peer_id, bool* state) { - LoggerD("Entered"); + ScopeLogger(); if (m_latest_peer_id != peer_id || !m_peer_handle) { *state = false; return PlatformResult(ErrorCode::NO_ERROR); @@ -679,7 +682,7 @@ PlatformResult NFCAdapter::PeerIsConnectedGetter(int peer_id, bool* state) { } PlatformResult NFCAdapter::SetPeerListener() { - LoggerD("Entered"); + ScopeLogger(); if (!nfc_manager_is_supported()) { return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NFC Not Supported"); } @@ -697,7 +700,7 @@ PlatformResult NFCAdapter::SetPeerListener() { } PlatformResult NFCAdapter::UnsetPeerListener() { - LoggerD("Entered"); + ScopeLogger(); if (!nfc_manager_is_supported()) { return LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NFC Not Supported"); } @@ -712,7 +715,7 @@ PlatformResult NFCAdapter::UnsetPeerListener() { static void targetReceivedCallback(nfc_p2p_target_h /*target*/, nfc_ndef_message_h message, void* /*data*/) { - LoggerD("Entered"); + ScopeLogger(); unsigned char* raw_data = NULL; unsigned int size; if (NFC_ERROR_NONE != nfc_ndef_message_get_rawdata(message, &raw_data, &size)) { @@ -734,7 +737,7 @@ static void targetReceivedCallback(nfc_p2p_target_h /*target*/, nfc_ndef_message } PlatformResult NFCAdapter::SetReceiveNDEFListener(int peer_id) { - LoggerD("Entered"); + ScopeLogger(); // unregister previous NDEF listener if (m_is_ndef_listener_set) { int ret = nfc_p2p_unset_data_received_cb(m_peer_handle); @@ -767,7 +770,7 @@ PlatformResult NFCAdapter::SetReceiveNDEFListener(int peer_id) { } PlatformResult NFCAdapter::UnsetReceiveNDEFListener(int peer_id) { - LoggerD("Entered"); + ScopeLogger(); if (m_is_ndef_listener_set) { // check if peer object is still connected @@ -794,13 +797,13 @@ PlatformResult NFCAdapter::UnsetReceiveNDEFListener(int peer_id) { } bool NFCAdapter::IsNDEFListenerSet() { - LoggerD("Entered"); + ScopeLogger(); return m_is_ndef_listener_set; } // NFCTag related functions PlatformResult NFCAdapter::TagTypeGetter(int /*tag_id*/, std::string* type) { - LoggerD("Entered"); + ScopeLogger(); nfc_tag_type_e nfc_type = NFC_UNKNOWN_TARGET; @@ -816,7 +819,7 @@ PlatformResult NFCAdapter::TagTypeGetter(int /*tag_id*/, std::string* type) { } PlatformResult NFCAdapter::TagIsSupportedNDEFGetter(int /*tag_id*/, bool* is_supported) { - LoggerD("Entered"); + ScopeLogger(); int err = nfc_tag_is_support_ndef(m_last_tag_handle, is_supported); if (NFC_ERROR_NONE != err) { @@ -828,7 +831,7 @@ PlatformResult NFCAdapter::TagIsSupportedNDEFGetter(int /*tag_id*/, bool* is_sup } PlatformResult NFCAdapter::TagNDEFSizeGetter(int /*tag_id*/, unsigned int* size) { - LoggerD("Entered"); + ScopeLogger(); int err = nfc_tag_get_ndef_size(m_last_tag_handle, size); if (NFC_ERROR_NONE != err) { @@ -840,7 +843,7 @@ PlatformResult NFCAdapter::TagNDEFSizeGetter(int /*tag_id*/, unsigned int* size) static bool tagPropertiesGetterCb(const char* key, const unsigned char* value, int value_size, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); if (user_data) { UCharVector tag_info = NFCUtil::ToVector(value, value_size); (static_cast(user_data))->push_back(std::make_pair(key, tag_info)); @@ -850,7 +853,7 @@ static bool tagPropertiesGetterCb(const char* key, const unsigned char* value, i } PlatformResult NFCAdapter::TagPropertiesGetter(int /*tag_id*/, NFCTagPropertiesT* properties) { - LoggerD("Entered"); + ScopeLogger(); int err = nfc_tag_foreach_information(m_last_tag_handle, tagPropertiesGetterCb, (void*)properties); @@ -863,7 +866,7 @@ PlatformResult NFCAdapter::TagPropertiesGetter(int /*tag_id*/, NFCTagPropertiesT } PlatformResult NFCAdapter::TagIsConnectedGetter(int tag_id, bool* state) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult result = PlatformResult(ErrorCode::NO_ERROR); @@ -895,12 +898,12 @@ PlatformResult NFCAdapter::TagIsConnectedGetter(int tag_id, bool* state) { } int NFCAdapter::GetNextTagId() { - LoggerD("Entered"); + ScopeLogger(); return ++m_latest_tag_id; } static void tagEventCallback(nfc_discovered_type_e type, nfc_tag_h tag, void* /*data*/) { - LoggerD("Entered"); + ScopeLogger(); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); @@ -938,7 +941,7 @@ static void tagEventCallback(nfc_discovered_type_e type, nfc_tag_h tag, void* /* } PlatformResult NFCAdapter::SetTagListener() { - LoggerD("Entered"); + ScopeLogger(); if (!m_is_tag_listener_set) { nfc_manager_set_tag_filter(NFC_TAG_FILTER_ALL_ENABLE); @@ -953,7 +956,7 @@ PlatformResult NFCAdapter::SetTagListener() { } void NFCAdapter::UnsetTagListener() { - LoggerD("Entered"); + ScopeLogger(); if (m_is_tag_listener_set) { nfc_manager_unset_tag_discovered_cb(); @@ -962,12 +965,12 @@ void NFCAdapter::UnsetTagListener() { } void NFCAdapter::SetTagHandle(nfc_tag_h tag) { - LoggerD("Entered"); + ScopeLogger(); m_last_tag_handle = tag; } static void tagReadNDEFCb(nfc_error_e result, nfc_ndef_message_h message, void* data) { - LoggerD("Entered"); + ScopeLogger(); if (!data) { // Can not continue if unable to get callbackId @@ -1016,7 +1019,7 @@ static void tagReadNDEFCb(nfc_error_e result, nfc_ndef_message_h message, void* } PlatformResult NFCAdapter::TagReadNDEF(int tag_id, const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); bool is_connected = false; PlatformResult result = TagIsConnectedGetter(tag_id, &is_connected); @@ -1062,7 +1065,7 @@ PlatformResult NFCAdapter::TagReadNDEF(int tag_id, const picojson::value& args) } PlatformResult NFCAdapter::TagWriteNDEF(int tag_id, const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); bool is_connected = false; PlatformResult result = TagIsConnectedGetter(tag_id, &is_connected); @@ -1129,7 +1132,7 @@ PlatformResult NFCAdapter::TagWriteNDEF(int tag_id, const picojson::value& args) } static void tagTransceiveCb(nfc_error_e err, unsigned char* buffer, int buffer_size, void* data) { - LoggerD("Entered"); + ScopeLogger(); std::unique_ptr buffer_ptr(buffer); buffer = nullptr; @@ -1164,7 +1167,7 @@ static void tagTransceiveCb(nfc_error_e err, unsigned char* buffer, int buffer_s } PlatformResult NFCAdapter::TagTransceive(int tag_id, const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); bool is_connected = false; PlatformResult result = TagIsConnectedGetter(tag_id, &is_connected); if (result.IsError()) { @@ -1221,7 +1224,7 @@ PlatformResult NFCAdapter::TagTransceive(int tag_id, const picojson::value& args } PlatformResult NFCAdapter::GetCachedMessage(picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); nfc_ndef_message_h message_handle = NULL; int result = nfc_manager_get_cached_message(&message_handle); if (NFC_ERROR_INVALID_NDEF_MESSAGE == result || NFC_ERROR_NO_NDEF_MESSAGE == result) { @@ -1254,7 +1257,7 @@ PlatformResult NFCAdapter::GetCachedMessage(picojson::object& out) { } static void peerSentCallback(nfc_error_e result, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); double* callbackId = static_cast(user_data); if (NFC_ERROR_NONE != result) { @@ -1274,13 +1277,13 @@ static void peerSentCallback(nfc_error_e result, void* user_data) { } static gboolean sendNDEFErrorCB(void* user_data) { - LoggerD("Entered"); + ScopeLogger(); peerSentCallback(NFC_ERROR_INVALID_NDEF_MESSAGE, user_data); return false; } PlatformResult NFCAdapter::sendNDEF(int peer_id, const picojson::value& args) { - LoggerD("Entered"); + ScopeLogger(); bool is_connected = false; PlatformResult result = PeerIsConnectedGetter(peer_id, &is_connected); if (result.IsError()) { @@ -1327,17 +1330,17 @@ PlatformResult NFCAdapter::sendNDEF(int peer_id, const picojson::value& args) { } void NFCAdapter::SetSEHandle(nfc_se_h handle) { - LoggerD("Entered"); + ScopeLogger(); m_se_handle = handle; } nfc_se_h NFCAdapter::GetSEHandle() { - LoggerD("Entered"); + ScopeLogger(); return m_se_handle; } PlatformResult NFCAdapter::AddHCEEventListener() { - LoggerD("Entered"); + ScopeLogger(); if (!m_is_hce_listener_set) { int ret = nfc_manager_set_hce_event_cb(HCEEventCallback, nullptr); if (NFC_ERROR_NONE != ret) { @@ -1350,7 +1353,7 @@ PlatformResult NFCAdapter::AddHCEEventListener() { } PlatformResult NFCAdapter::RemoveHCEEventListener() { - LoggerD("Entered"); + ScopeLogger(); if (m_is_hce_listener_set) { nfc_manager_unset_hce_event_cb(); m_is_hce_listener_set = false; @@ -1361,7 +1364,7 @@ PlatformResult NFCAdapter::RemoveHCEEventListener() { void NFCAdapter::SendHostAPDUResponse(const UCharVector& apdu, const std::function& success_cb, const std::function& error_cb) { - LoggerD("Entered"); + ScopeLogger(); if (!nfc_manager_is_supported()) { error_cb(LogAndCreateResult(ErrorCode::NOT_SUPPORTED_ERR, "NFC Not Supported")); @@ -1380,8 +1383,8 @@ void NFCAdapter::SendHostAPDUResponse(const UCharVector& apdu, PlatformResult NFCAdapter::IsActivatedHandlerForAID(const std::string& type, const std::string& aid, bool* is_activated_handler) { + ScopeLogger(); AssertMsg(is_activated_handler, "Poiner can not be null!"); - LoggerD("Entered"); nfc_se_type_e se_type; PlatformResult result = NFCUtil::ToSecureElementType(type, &se_type); @@ -1401,7 +1404,7 @@ PlatformResult NFCAdapter::IsActivatedHandlerForAID(const std::string& type, con PlatformResult NFCAdapter::IsActivatedHandlerForCategory( const std::string& type, nfc_card_emulation_category_type_e category, bool* is_activated_handler) { - LoggerD("Entered"); + ScopeLogger(); AssertMsg(is_activated_handler, "Poiner can not be null!"); nfc_se_type_e se_type; @@ -1421,7 +1424,7 @@ PlatformResult NFCAdapter::IsActivatedHandlerForCategory( PlatformResult NFCAdapter::RegisterAID(const std::string& type, const std::string& aid, nfc_card_emulation_category_type_e category) { - LoggerD("Entered"); + ScopeLogger(); nfc_se_type_e se_type; PlatformResult result = NFCUtil::ToSecureElementType(type, &se_type); if (result.IsError()) { @@ -1439,7 +1442,7 @@ PlatformResult NFCAdapter::RegisterAID(const std::string& type, const std::strin PlatformResult NFCAdapter::UnregisterAID(const std::string& type, const std::string& aid, nfc_card_emulation_category_type_e category) { - LoggerD("Entered"); + ScopeLogger(); nfc_se_type_e se_type; PlatformResult result = NFCUtil::ToSecureElementType(type, &se_type); if (result.IsError()) { @@ -1456,7 +1459,7 @@ PlatformResult NFCAdapter::UnregisterAID(const std::string& type, const std::str } static void SaveRow(nfc_se_type_e se_type, const char* aid, bool read_only, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); AssertMsg(aid, "Poiner can not be null!"); AssertMsg(user_data, "Poiner can not be null!"); AIDDataVector* aids = static_cast(user_data); @@ -1468,7 +1471,7 @@ void NFCAdapter::GetAIDsForCategory(const std::string& type, nfc_card_emulation_category_type_e category, const std::function& success_cb, const std::function& error_cb) { - LoggerD("Entered"); + ScopeLogger(); nfc_se_type_e se_type; PlatformResult result = NFCUtil::ToSecureElementType(type, &se_type); if (result.IsError()) { diff --git a/src/nfc/nfc_extension.cc b/src/nfc/nfc_extension.cc index 4d0d044..b778fed 100644 --- a/src/nfc/nfc_extension.cc +++ b/src/nfc/nfc_extension.cc @@ -26,7 +26,7 @@ common::Extension* CreateExtension() { } NFCExtension::NFCExtension() { - LoggerD("Entered"); + ScopeLogger(); SetExtensionName("tizen.nfc"); SetJavaScriptAPI(kSource_nfc_api); @@ -37,10 +37,10 @@ NFCExtension::NFCExtension() { } NFCExtension::~NFCExtension() { - LoggerD("Entered"); + ScopeLogger(); } common::Instance* NFCExtension::CreateInstance() { - LoggerD("Entered"); + ScopeLogger(); return new extension::nfc::NFCInstance(); } diff --git a/src/nfc/nfc_instance.cc b/src/nfc/nfc_instance.cc index 337bcd6..70c5dcc 100644 --- a/src/nfc/nfc_instance.cc +++ b/src/nfc/nfc_instance.cc @@ -47,12 +47,12 @@ const std::string kPrivilegeNfcTag = "http://tizen.org/privilege/nfc.tag"; } // namespace void NFCInstance::RespondAsync(const char* msg) { - LoggerD("Entered"); + ScopeLogger(); Instance::PostMessage(this, msg); } static bool isTagSupported() { - LoggerD("Entered"); + ScopeLogger(); bool supported = true; if (system_info_get_platform_bool("http://tizen.org/feature/network.nfc.tag", &supported) != SYSTEM_INFO_ERROR_NONE) { @@ -62,7 +62,7 @@ static bool isTagSupported() { } static bool isP2PSupported() { - LoggerD("Entered"); + ScopeLogger(); bool supported = true; if (system_info_get_platform_bool("http://tizen.org/feature/network.nfc.p2p", &supported) != SYSTEM_INFO_ERROR_NONE) { @@ -72,7 +72,7 @@ static bool isP2PSupported() { } NFCInstance::NFCInstance() { - LoggerD("Entered"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; #define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&NFCInstance::x, this, _1, _2)); @@ -150,14 +150,14 @@ NFCInstance::NFCInstance() { } NFCInstance::~NFCInstance() { - LoggerD("Entered"); + ScopeLogger(); NFCAdapter::GetInstance()->SetResponder(nullptr); } void NFCInstance::GetDefaultAdapter(const picojson::value& args, picojson::object& out) { // Default NFC adapter is created at JS level // Here there's only check for NFC support - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCommon, &out); @@ -171,7 +171,7 @@ void NFCInstance::GetDefaultAdapter(const picojson::value& args, picojson::objec } void NFCInstance::SetExclusiveMode(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCommon, &out); CHECK_EXIST(args, "exclusiveMode", out); @@ -190,7 +190,7 @@ void NFCInstance::SetExclusiveMode(const picojson::value& args, picojson::object // TODO(g.rynkowski): Rewrite to asynchronous approach void NFCInstance::SetPowered(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); LoggerW( "DEPRECATION WARNING: setPowered() is deprecated and will be removed from next release. Let " "the user turn NFC on/off " @@ -207,13 +207,13 @@ void NFCInstance::SetPowered(const picojson::value& args, picojson::object& out) } void NFCInstance::GetPowered(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); bool ret = NFCAdapter::GetInstance()->GetPowered(); ReportSuccess(picojson::value(ret), out); } void NFCInstance::CardEmulationModeSetter(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); CHECK_EXIST(args, "emulationMode", out); @@ -227,7 +227,7 @@ void NFCInstance::CardEmulationModeSetter(const picojson::value& args, picojson: } void NFCInstance::CardEmulationModeGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); std::string mode = ""; @@ -240,7 +240,7 @@ void NFCInstance::CardEmulationModeGetter(const picojson::value& args, picojson: } void NFCInstance::ActiveSecureElementSetter(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); CHECK_EXIST(args, "secureElement", out); @@ -254,7 +254,7 @@ void NFCInstance::ActiveSecureElementSetter(const picojson::value& args, picojso } void NFCInstance::ActiveSecureElementGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); std::string ase = ""; @@ -267,7 +267,7 @@ void NFCInstance::ActiveSecureElementGetter(const picojson::value& args, picojso } void NFCInstance::SetTagListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcTag, &out); bool supported = isTagSupported(); if (supported) { @@ -287,7 +287,7 @@ void NFCInstance::SetTagListener(const picojson::value& args, picojson::object& } void NFCInstance::PeerIsConnectedGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, "id", out); int peer_id = (int)args.get("id").get(); @@ -302,7 +302,7 @@ void NFCInstance::PeerIsConnectedGetter(const picojson::value& args, picojson::o } void NFCInstance::SetPeerListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcP2P, &out); bool supported = isP2PSupported(); if (supported) { @@ -322,7 +322,7 @@ void NFCInstance::SetPeerListener(const picojson::value& args, picojson::object& } void NFCInstance::UnsetTagListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcTag, &out); bool supported = isTagSupported(); if (supported) { @@ -338,7 +338,7 @@ void NFCInstance::UnsetTagListener(const picojson::value& args, picojson::object } void NFCInstance::UnsetPeerListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcP2P, &out); bool supported = isP2PSupported(); if (supported) { @@ -359,7 +359,7 @@ void NFCInstance::UnsetPeerListener(const picojson::value& args, picojson::objec void NFCInstance::AddCardEmulationModeChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); PlatformResult result = NFCAdapter::GetInstance()->AddCardEmulationModeChangeListener(); @@ -372,7 +372,7 @@ void NFCInstance::AddCardEmulationModeChangeListener(const picojson::value& args void NFCInstance::RemoveCardEmulationModeChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); PlatformResult result = NFCAdapter::GetInstance()->RemoveCardEmulationModeChangeListener(); @@ -384,7 +384,7 @@ void NFCInstance::RemoveCardEmulationModeChangeListener(const picojson::value& a } void NFCInstance::AddTransactionEventListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); PlatformResult result = NFCAdapter::GetInstance()->AddTransactionEventListener(args); @@ -397,7 +397,7 @@ void NFCInstance::AddTransactionEventListener(const picojson::value& args, picoj void NFCInstance::RemoveTransactionEventListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); PlatformResult result = NFCAdapter::GetInstance()->RemoveTransactionEventListener(args); @@ -410,7 +410,7 @@ void NFCInstance::RemoveTransactionEventListener(const picojson::value& args, void NFCInstance::AddActiveSecureElementChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); PlatformResult result = NFCAdapter::GetInstance()->AddActiveSecureElementChangeListener(); @@ -423,7 +423,7 @@ void NFCInstance::AddActiveSecureElementChangeListener(const picojson::value& ar void NFCInstance::RemoveActiveSecureElementChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); PlatformResult result = NFCAdapter::GetInstance()->RemoveActiveSecureElementChangeListener(); @@ -435,7 +435,7 @@ void NFCInstance::RemoveActiveSecureElementChangeListener(const picojson::value& } void NFCInstance::GetCachedMessage(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCommon, &out); picojson::value result = picojson::value(picojson::object()); @@ -451,7 +451,7 @@ void NFCInstance::GetCachedMessage(const picojson::value& args, picojson::object void NFCInstance::SetExclusiveModeForTransaction(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); CHECK_EXIST(args, "transactionMode", out); @@ -468,7 +468,7 @@ void NFCInstance::SetExclusiveModeForTransaction(const picojson::value& args, // TODO(g.rynkowski): Rewrite to asynchronous approach void NFCInstance::ReadNDEF(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcTag, &out); CHECK_EXIST(args, "id", out); @@ -486,7 +486,7 @@ void NFCInstance::ReadNDEF(const picojson::value& args, picojson::object& out) { // TODO(g.rynkowski): Rewrite to asynchronous approach void NFCInstance::WriteNDEF(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcTag, &out); CHECK_EXIST(args, "id", out); @@ -504,7 +504,7 @@ void NFCInstance::WriteNDEF(const picojson::value& args, picojson::object& out) // TODO(g.rynkowski): Rewrite to asynchronous approach void NFCInstance::Transceive(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcTag, &out); CHECK_EXIST(args, "id", out); @@ -520,7 +520,7 @@ void NFCInstance::Transceive(const picojson::value& args, picojson::object& out) } void NFCInstance::SetReceiveNDEFListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcP2P, &out); CHECK_EXIST(args, "id", out); @@ -535,7 +535,7 @@ void NFCInstance::SetReceiveNDEFListener(const picojson::value& args, picojson:: } void NFCInstance::UnsetReceiveNDEFListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcP2P, &out); CHECK_EXIST(args, "id", out); @@ -551,7 +551,7 @@ void NFCInstance::UnsetReceiveNDEFListener(const picojson::value& args, picojson // TODO(g.rynkowski): Rewrite to asynchronous approach void NFCInstance::SendNDEF(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcP2P, &out); CHECK_EXIST(args, "id", out); @@ -569,7 +569,7 @@ void NFCInstance::SendNDEF(const picojson::value& args, picojson::object& out) { } void NFCInstance::ToByte(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); @@ -584,7 +584,7 @@ void NFCInstance::ToByte(const picojson::value& args, picojson::object& out) { // Message related methods void NFCInstance::NDEFMessageContructor(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); PlatformResult ret = NFCMessageUtils::ReportNDEFMessage(args, result_obj); @@ -597,7 +597,7 @@ void NFCInstance::NDEFMessageContructor(const picojson::value& args, picojson::o } void NFCInstance::NDEFRecordContructor(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); PlatformResult ret = NFCMessageUtils::ReportNDEFRecord(args, result_obj); @@ -610,7 +610,7 @@ void NFCInstance::NDEFRecordContructor(const picojson::value& args, picojson::ob } void NFCInstance::NDEFRecordTextContructor(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); @@ -624,7 +624,7 @@ void NFCInstance::NDEFRecordTextContructor(const picojson::value& args, picojson } void NFCInstance::NDEFRecordURIContructor(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); PlatformResult ret = NFCMessageUtils::ReportNDEFRecordURI(args, result_obj); @@ -637,7 +637,7 @@ void NFCInstance::NDEFRecordURIContructor(const picojson::value& args, picojson: } void NFCInstance::NDEFRecordMediaContructor(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); @@ -652,7 +652,7 @@ void NFCInstance::NDEFRecordMediaContructor(const picojson::value& args, picojso // NFCTag attributes getters void NFCInstance::TagTypeGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, "id", out); int tag_id = (int)args.get("id").get(); @@ -686,7 +686,7 @@ void NFCInstance::TagTypeGetter(const picojson::value& args, picojson::object& o } void NFCInstance::TagIsSupportedNDEFGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); int tag_id = (int)args.get("id").get(); LoggerD("Tag id: %d", tag_id); @@ -718,7 +718,7 @@ void NFCInstance::TagIsSupportedNDEFGetter(const picojson::value& args, picojson } void NFCInstance::TagNDEFSizeGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); int tag_id = (int)args.get("id").get(); LoggerD("Tag id: %d", tag_id); @@ -751,7 +751,7 @@ void NFCInstance::TagNDEFSizeGetter(const picojson::value& args, picojson::objec } void NFCInstance::TagPropertiesGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); int tag_id = (int)args.get("id").get(); LoggerD("Tag id: %d", tag_id); @@ -800,7 +800,7 @@ void NFCInstance::TagPropertiesGetter(const picojson::value& args, picojson::obj } void NFCInstance::TagIsConnectedGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, "id", out); int tag_id = (int)args.get("id").get(); @@ -817,7 +817,7 @@ void NFCInstance::TagIsConnectedGetter(const picojson::value& args, picojson::ob } void NFCInstance::AddHCEEventListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); PlatformResult result = NFCAdapter::GetInstance()->AddHCEEventListener(); @@ -829,7 +829,7 @@ void NFCInstance::AddHCEEventListener(const picojson::value& args, picojson::obj } void NFCInstance::RemoveHCEEventListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); PlatformResult result = NFCAdapter::GetInstance()->RemoveHCEEventListener(); @@ -841,7 +841,7 @@ void NFCInstance::RemoveHCEEventListener(const picojson::value& args, picojson:: } void NFCInstance::SendHostAPDUResponse(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); CHECK_EXIST(args, JSON_APDU, out); @@ -851,7 +851,7 @@ void NFCInstance::SendHostAPDUResponse(const picojson::value& args, picojson::ob const double& callback_id = args.get(JSON_CALLBACK_ID).get(); auto success_cb = [this, callback_id]() -> void { - LoggerD("Entered"); + ScopeLogger("Entered into asynchronous function, success_cb"); picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); response_obj[JSON_CALLBACK_ID] = picojson::value(callback_id); @@ -860,7 +860,7 @@ void NFCInstance::SendHostAPDUResponse(const picojson::value& args, picojson::ob }; auto error_cb = [this, callback_id](const PlatformResult& error) -> void { - LoggerD("Entered error_cb: %s", error.message().c_str()); + ScopeLogger("Entered into asynchronous function, error_cb: %s", error.message().c_str()); picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); response_obj[JSON_CALLBACK_ID] = picojson::value(callback_id); @@ -873,7 +873,7 @@ void NFCInstance::SendHostAPDUResponse(const picojson::value& args, picojson::ob } void NFCInstance::IsActivatedHandlerForAID(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); CHECK_EXIST(args, JSON_TYPE, out); @@ -893,7 +893,7 @@ void NFCInstance::IsActivatedHandlerForAID(const picojson::value& args, picojson void NFCInstance::IsActivatedHandlerForCategory(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); CHECK_EXIST(args, JSON_TYPE, out); @@ -913,7 +913,7 @@ void NFCInstance::IsActivatedHandlerForCategory(const picojson::value& args, } void NFCInstance::RegisterAID(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); CHECK_EXIST(args, JSON_TYPE, out); @@ -933,7 +933,7 @@ void NFCInstance::RegisterAID(const picojson::value& args, picojson::object& out } void NFCInstance::UnregisterAID(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); CHECK_EXIST(args, JSON_TYPE, out); @@ -953,7 +953,7 @@ void NFCInstance::UnregisterAID(const picojson::value& args, picojson::object& o } void NFCInstance::GetAIDsForCategory(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNfcCardEmulation, &out); CHECK_EXIST(args, JSON_TYPE, out); @@ -964,7 +964,7 @@ void NFCInstance::GetAIDsForCategory(const picojson::value& args, picojson::obje const double& callback_id = args.get(JSON_CALLBACK_ID).get(); auto success_cb = [this, callback_id](const AIDDataVector& data) -> void { - LoggerD("enter"); + ScopeLogger("Entered into asynchronous function, success_cb"); picojson::array aids; aids.reserve(data.size()); for (const auto& aid : data) { @@ -978,7 +978,7 @@ void NFCInstance::GetAIDsForCategory(const picojson::value& args, picojson::obje }; auto error_cb = [this, callback_id](const PlatformResult& error) -> void { - LoggerD("entered error_cb: %s", error.message().c_str()); + ScopeLogger("Entered into asynchronous function, error_cb: %s", error.message().c_str()); picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); response_obj[JSON_CALLBACK_ID] = picojson::value(callback_id); diff --git a/src/nfc/nfc_message_utils.cc b/src/nfc/nfc_message_utils.cc index cc1d076..4581c5e 100644 --- a/src/nfc/nfc_message_utils.cc +++ b/src/nfc/nfc_message_utils.cc @@ -51,7 +51,7 @@ enum nfcTNF { /* -------------------------------COMMON FUNCTIONS------------------------------------ */ void NFCMessageUtils::RemoveMessageHandle(nfc_ndef_message_h message_handle) { - LoggerD("Entered"); + ScopeLogger(); if (message_handle) { int result = nfc_ndef_message_destroy(message_handle); if (NFC_ERROR_NONE != result) { @@ -63,7 +63,7 @@ void NFCMessageUtils::RemoveMessageHandle(nfc_ndef_message_h message_handle) { } static void removeRecordHandle(nfc_ndef_record_h record_handle) { - LoggerD("Entered"); + ScopeLogger(); if (record_handle) { int result = nfc_ndef_record_destroy(record_handle); if (NFC_ERROR_NONE != result) { @@ -76,7 +76,7 @@ static void removeRecordHandle(nfc_ndef_record_h record_handle) { static PlatformResult getTnfFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, short* tnf) { - LoggerD("Entered"); + ScopeLogger(); nfc_record_tnf_e record_tnf; int result = nfc_ndef_record_get_tnf(handle, &record_tnf); if (NFC_ERROR_NONE != result) { @@ -98,7 +98,7 @@ static PlatformResult getTnfFromHandle(nfc_ndef_record_h handle, nfc_ndef_messag static PlatformResult getTypeNameFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, UCharVector* type) { - LoggerD("Entered"); + ScopeLogger(); unsigned char* type_name; int type_size, result; @@ -120,7 +120,7 @@ static PlatformResult getTypeNameFromHandle(nfc_ndef_record_h handle, static PlatformResult getIdFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, UCharVector* id) { - LoggerD("Entered"); + ScopeLogger(); unsigned char* tmp_id; int id_size, result; @@ -144,7 +144,7 @@ static PlatformResult getIdFromHandle(nfc_ndef_record_h handle, nfc_ndef_message static PlatformResult getPayloadFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, UCharVector* payload) { - LoggerD("Entered"); + ScopeLogger(); unsigned char* tmp_payload; unsigned int payload_size; int result; @@ -168,7 +168,7 @@ static PlatformResult getPayloadFromHandle(nfc_ndef_record_h handle, } static nfc_encode_type_e convertToNfcEncodeUTF(const std::string& encode_string) { - LoggerD("Entered"); + ScopeLogger(); if (NFC_TEXT_UTF16 == encode_string) { return NFC_ENCODE_UTF_16; } else { @@ -177,7 +177,7 @@ static nfc_encode_type_e convertToNfcEncodeUTF(const std::string& encode_string) } static std::string convertEncodingToString(nfc_encode_type_e encoding) { - LoggerD("Entered"); + ScopeLogger(); if (encoding == NFC_ENCODE_UTF_16) { return NFC_TEXT_UTF16; } else { @@ -188,7 +188,7 @@ static std::string convertEncodingToString(nfc_encode_type_e encoding) { /* -------------------------------MESSAGE FUNCTIONS------------------------------------ */ PlatformResult NFCMessageUtils::ToNdefRecords(const nfc_ndef_message_h message, picojson::array& array) { - LoggerD("Entered"); + ScopeLogger(); if (NULL != message) { int count; int result = nfc_ndef_message_get_record_count(message, &count); @@ -266,7 +266,7 @@ PlatformResult NFCMessageUtils::ToNdefRecords(const nfc_ndef_message_h message, PlatformResult NFCMessageUtils::ReportNdefMessageFromData(unsigned char* data, unsigned long size, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); nfc_ndef_message_h message = NULL; int result = nfc_ndef_message_create_from_rawdata(&message, data, size); @@ -293,7 +293,7 @@ PlatformResult NFCMessageUtils::ReportNdefMessageFromData(unsigned char* data, u PlatformResult NFCMessageUtils::ReportNDEFMessage(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const picojson::array& raw_data = FromJson(args.get(), "rawData"); const int size = static_cast(args.get("rawDataSize").get()); @@ -309,7 +309,7 @@ PlatformResult NFCMessageUtils::ReportNDEFMessage(const picojson::value& args, static PlatformResult NdefRecordGetHandle(picojson::value& record, nfc_ndef_record_h* record_handle) { - LoggerD("Entered"); + ScopeLogger(); if (!record.is() || !record.contains("tnf") || !record.contains("type") || !record.contains("id") || !record.contains("payload")) { return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Record is empty"); @@ -355,7 +355,7 @@ static PlatformResult NdefRecordGetHandle(picojson::value& record, PlatformResult NFCMessageUtils::NDEFMessageToStruct(const picojson::array& records_array, const int size, nfc_ndef_message_h* message) { - LoggerD("Entered"); + ScopeLogger(); if (!size) { LoggerE("No records in message"); return PlatformResult(ErrorCode::NO_ERROR); @@ -396,7 +396,7 @@ PlatformResult NFCMessageUtils::NDEFMessageToStruct(const picojson::array& recor PlatformResult NFCMessageUtils::NDEFMessageToByte(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); // input const picojson::array& records_array = FromJson(args.get(), "records"); @@ -447,7 +447,7 @@ PlatformResult NFCMessageUtils::NDEFMessageToByte(const picojson::value& args, /* -------------------------------RECORD FUNCTIONS------------------------------------ */ static void ConstructRecordJson(short _tnf, const UCharVector& _type_name, const UCharVector& _id, const UCharVector& _payload, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); out.insert(std::make_pair("tnf", picojson::value(std::to_string(_tnf)))); picojson::value type_array = picojson::value(picojson::array()); @@ -474,7 +474,7 @@ static void ConstructRecordJson(short _tnf, const UCharVector& _type_name, const PlatformResult NFCMessageUtils::ConstructNdefRecordFromRecordHandle(nfc_ndef_record_h record_handle, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); short _tnf; PlatformResult ret = getTnfFromHandle(record_handle, NULL, &_tnf); @@ -509,7 +509,7 @@ PlatformResult NFCMessageUtils::ConstructNdefRecordFromRecordHandle(nfc_ndef_rec PlatformResult NFCMessageUtils::ReportNdefRecordFromMessage(nfc_ndef_message_h message_handle, const int index, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); nfc_ndef_record_h record_handle = NULL; int result = nfc_ndef_message_get_record(message_handle, index, &record_handle); if (NFC_ERROR_NONE != result) { @@ -523,7 +523,7 @@ PlatformResult NFCMessageUtils::ReportNdefRecordFromMessage(nfc_ndef_message_h m PlatformResult NFCMessageUtils::ReportNDEFRecord(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const picojson::array& raw_data = FromJson(args.get(), "rawData"); const int size = static_cast(args.get("rawDataSize").get()); @@ -565,7 +565,7 @@ PlatformResult NFCMessageUtils::ReportNDEFRecord(const picojson::value& args, /* -------------------------------RECORD TEXT FUNCTIONS------------------------------------ */ static PlatformResult getTextFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, std::string* text) { - LoggerD("Entered"); + ScopeLogger(); char* tmp_text = NULL; int result = nfc_ndef_record_get_text(handle, &tmp_text); if (NFC_ERROR_NONE != result) { @@ -584,7 +584,7 @@ static PlatformResult getTextFromHandle(nfc_ndef_record_h handle, nfc_ndef_messa static PlatformResult getLanguageCodeFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, std::string* language) { - LoggerD("Entered"); + ScopeLogger(); char* language_code = NULL; int result = nfc_ndef_record_get_langcode(handle, &language_code); if (NFC_ERROR_NONE != result) { @@ -604,7 +604,7 @@ static PlatformResult getLanguageCodeFromHandle(nfc_ndef_record_h handle, static PlatformResult getEncodingFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, nfc_encode_type_e* encoding_type) { - LoggerD("Entered"); + ScopeLogger(); nfc_encode_type_e encoding; int result = nfc_ndef_record_get_encode_type(handle, &encoding); if (NFC_ERROR_NONE != result) { @@ -622,7 +622,7 @@ static PlatformResult ReportNDEFRecordTextFromText(const std::string& text, const std::string& language_code, const std::string& encoding_str, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); nfc_encode_type_e encoding = convertToNfcEncodeUTF(encoding_str); nfc_ndef_record_h handle = NULL; @@ -668,7 +668,7 @@ static PlatformResult ReportNDEFRecordTextFromText(const std::string& text, PlatformResult NFCMessageUtils::ReportNdefRecordTextFromMessage(nfc_ndef_message_h message_handle, const int index, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); nfc_ndef_record_h record_handle = NULL; // This function just return the pointer of record. int result = nfc_ndef_message_get_record(message_handle, index, &record_handle); @@ -714,7 +714,7 @@ PlatformResult NFCMessageUtils::ReportNdefRecordTextFromMessage(nfc_ndef_message PlatformResult NFCMessageUtils::ReportNDEFRecordText(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const std::string& text = args.get("text").get(); const std::string& language_code = args.get("languageCode").get(); const std::string& encoding_str = args.get("encoding").get(); @@ -725,7 +725,7 @@ PlatformResult NFCMessageUtils::ReportNDEFRecordText(const picojson::value& args /* -------------------------------RECORD URI FUNCTIONS------------------------------------ */ static PlatformResult getURIFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, std::string* uri_handle) { - LoggerD("Entered"); + ScopeLogger(); char* uri = NULL; int result = nfc_ndef_record_get_uri(handle, &uri); if (NFC_ERROR_NONE != result || !uri) { @@ -742,7 +742,7 @@ static PlatformResult getURIFromHandle(nfc_ndef_record_h handle, nfc_ndef_messag } static PlatformResult ReportNDEFRecordURIFromURI(const std::string& uri, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); nfc_ndef_record_h handle = NULL; int result = nfc_ndef_record_create_uri(&handle, uri.c_str()); @@ -787,7 +787,7 @@ static PlatformResult ReportNDEFRecordURIFromURI(const std::string& uri, picojso PlatformResult NFCMessageUtils::ReportNdefRecordURIFromMessage(nfc_ndef_message_h message_handle, const int index, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); nfc_ndef_record_h record_handle = NULL; // This function just return the pointer of record. int result = nfc_ndef_message_get_record(message_handle, index, &record_handle); @@ -814,7 +814,7 @@ PlatformResult NFCMessageUtils::ReportNdefRecordURIFromMessage(nfc_ndef_message_ PlatformResult NFCMessageUtils::ReportNDEFRecordURI(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const std::string& uri = args.get("uri").get(); return ReportNDEFRecordURIFromURI(uri, out); @@ -823,7 +823,7 @@ PlatformResult NFCMessageUtils::ReportNDEFRecordURI(const picojson::value& args, /* -------------------------------RECORD MEDIA FUNCTIONS------------------------------------ */ static PlatformResult getMimeTypeFromHandle(nfc_ndef_record_h handle, nfc_ndef_message_h message_handle, std::string* mime) { - LoggerD("Entered"); + ScopeLogger(); char* mime_type = NULL; int result = nfc_ndef_record_get_mime_type(handle, &mime_type); if (NFC_ERROR_NONE != result) { @@ -843,7 +843,7 @@ static PlatformResult getMimeTypeFromHandle(nfc_ndef_record_h handle, PlatformResult NFCMessageUtils::ReportNdefRecordMediaFromMessage(nfc_ndef_message_h message_handle, const int index, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); nfc_ndef_record_h record_handle = NULL; // This function just return the pointer of record. int result = nfc_ndef_message_get_record(message_handle, index, &record_handle); @@ -892,7 +892,7 @@ PlatformResult NFCMessageUtils::ReportNdefRecordMediaFromMessage(nfc_ndef_messag PlatformResult NFCMessageUtils::ReportNDEFRecordMedia(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const std::string& mime_type = args.get("mimeType").get(); const picojson::array& raw_data = FromJson(args.get(), "data"); diff --git a/src/nfc/nfc_util.cc b/src/nfc/nfc_util.cc index 33f0990..46be48b 100644 --- a/src/nfc/nfc_util.cc +++ b/src/nfc/nfc_util.cc @@ -27,13 +27,13 @@ namespace extension { namespace nfc { UCharVector NFCUtil::ToVector(const unsigned char* ch, const int size) { - LoggerD("Entered"); + ScopeLogger(); UCharVector vec(ch, ch + size / sizeof(char)); return vec; } PlatformResult NFCUtil::CodeToResult(const int errorCode, const std::string& message) { - LoggerD("Entered"); + ScopeLogger(); switch (errorCode) { case NFC_ERROR_INVALID_PARAMETER: case NFC_ERROR_INVALID_NDEF_MESSAGE: @@ -59,7 +59,7 @@ PlatformResult NFCUtil::CodeToResult(const int errorCode, const std::string& mes } std::string NFCUtil::getNFCErrorString(const int error_code) { - LoggerD("Error code : %d", error_code); + ScopeLogger("Error code : %d", error_code); switch (error_code) { case NFC_ERROR_ALREADY_ACTIVATED: case NFC_ERROR_ALREADY_DEACTIVATED: @@ -85,7 +85,7 @@ std::string NFCUtil::getNFCErrorString(const int error_code) { } const std::string NFCUtil::getNFCErrorMessage(const int error_code) { - LoggerD("Error code : %d", error_code); + ScopeLogger("Error code : %d", error_code); switch (error_code) { case NFC_ERROR_ALREADY_ACTIVATED: case NFC_ERROR_ALREADY_DEACTIVATED: @@ -126,7 +126,7 @@ const std::string NFCUtil::getNFCErrorMessage(const int error_code) { } std::string NFCUtil::ToStringNFCTag(nfc_tag_type_e tag_type) { - LoggerD("Entered"); + ScopeLogger(); switch (tag_type) { case NFC_GENERIC_PICC: return GENERIC_TARGET; @@ -165,7 +165,7 @@ std::string NFCUtil::ToStringNFCTag(nfc_tag_type_e tag_type) { } PlatformResult NFCUtil::ToNfcTagString(const std::string& type_string, nfc_tag_type_e* tag_type) { - LoggerD("Entered"); + ScopeLogger(); if (GENERIC_TARGET == type_string) { *tag_type = NFC_GENERIC_PICC; } else if (ISO14443_A == type_string) { @@ -206,7 +206,7 @@ PlatformResult NFCUtil::ToNfcTagString(const std::string& type_string, nfc_tag_t PlatformResult NFCUtil::ToStringCardEmulationMode(const nfc_se_card_emulation_mode_type_e card_mode, std::string* mode) { - LoggerD("Entered"); + ScopeLogger(); switch (card_mode) { case NFC_SE_CARD_EMULATION_MODE_OFF: *mode = OFF; @@ -223,7 +223,7 @@ PlatformResult NFCUtil::ToStringCardEmulationMode(const nfc_se_card_emulation_mo PlatformResult NFCUtil::ToCardEmulationMode(const std::string& mode_string, nfc_se_card_emulation_mode_type_e* mode) { - LoggerD("Entered"); + ScopeLogger(); if (mode_string == ALWAYS_ON) { *mode = NFC_SE_CARD_EMULATION_MODE_ON; } else if (mode_string == OFF) { @@ -236,7 +236,7 @@ PlatformResult NFCUtil::ToCardEmulationMode(const std::string& mode_string, } PlatformResult NFCUtil::ToStringSecureElementType(const nfc_se_type_e se_type, std::string* type) { - LoggerD("Entered"); + ScopeLogger(); switch (se_type) { case NFC_SE_TYPE_ESE: *type = DATA_NFC_SE_TYPE_ESE; @@ -255,7 +255,7 @@ PlatformResult NFCUtil::ToStringSecureElementType(const nfc_se_type_e se_type, s } PlatformResult NFCUtil::ToSecureElementType(const std::string& type_string, nfc_se_type_e* type) { - LoggerD("Entered"); + ScopeLogger(); if (type_string == DATA_NFC_SE_TYPE_ESE) { *type = NFC_SE_TYPE_ESE; } else if (type_string == DATA_NFC_SE_TYPE_UICC) { @@ -270,7 +270,7 @@ PlatformResult NFCUtil::ToSecureElementType(const std::string& type_string, nfc_ } void NFCUtil::setDefaultFilterValues(std::vector& filter) { - LoggerD("Entered"); + ScopeLogger(); filter.push_back(NFC_GENERIC_PICC); filter.push_back(NFC_ISO14443_A_PICC); filter.push_back(NFC_ISO14443_3A_PICC); @@ -291,7 +291,7 @@ void NFCUtil::setDefaultFilterValues(std::vector& filter) { // Convertion of enum to HCEEventType(characters sequence). const char* NFCUtil::ToStr(nfc_hce_event_type_e event_type) { - LoggerD("Entered"); + ScopeLogger(); switch (event_type) { case NFC_HCE_EVENT_DEACTIVATED: return "DEACTIVATED"; @@ -307,7 +307,7 @@ const char* NFCUtil::ToStr(nfc_hce_event_type_e event_type) { // Convertion of enum to SecureElementType(characters sequence). // Warning! DISABLE and SDCARD are not mentioned at widl spec. const char* NFCUtil::ToStr(nfc_se_type_e se_type) { - LoggerD("Entered"); + ScopeLogger(); switch (se_type) { case NFC_SE_TYPE_DISABLE: return "DISABLE"; @@ -326,14 +326,14 @@ const char* NFCUtil::ToStr(nfc_se_type_e se_type) { // Convertion CardEmulationCategoryType(characters sequence) to enum. nfc_card_emulation_category_type_e NFCUtil::StringToCategory(const std::string& category_type) { - LoggerD("Entered"); + ScopeLogger(); if (category_type == "PAYMENT") return NFC_CARD_EMULATION_CATEGORY_PAYMENT; if (category_type == "OTHER") return NFC_CARD_EMULATION_CATEGORY_OTHER; AssertMsg(false, "That category type is incorrect."); } unsigned char* NFCUtil::DoubleArrayToUCharArray(const picojson::array& array_in) { - LoggerD("Entered"); + ScopeLogger(); unsigned char* result_array = new unsigned char[array_in.size()]; for (std::size_t i = 0; i < array_in.size(); ++i) { result_array[i] = static_cast(array_in.at(i).get()); @@ -342,12 +342,12 @@ unsigned char* NFCUtil::DoubleArrayToUCharArray(const picojson::array& array_in) } UCharVector NFCUtil::DoubleArrayToUCharVector(const picojson::array& array_in) { - LoggerD("Entered"); + ScopeLogger(); return ToVector(NFCUtil::DoubleArrayToUCharArray(array_in), array_in.size()); } picojson::array NFCUtil::FromUCharArray(unsigned char* array, unsigned int apdu_len) { - LoggerD("Entered"); + ScopeLogger(); picojson::array apdu_array; apdu_array.reserve(apdu_len); for (unsigned int i = 0; i < apdu_len; ++i) diff --git a/src/notification/notification_instance.cc b/src/notification/notification_instance.cc index 8e8e356..a75aafa 100644 --- a/src/notification/notification_instance.cc +++ b/src/notification/notification_instance.cc @@ -37,7 +37,7 @@ const std::string kPrivilegeLED = "http://tizen.org/privilege/led"; using namespace common; NotificationInstance::NotificationInstance() { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; #define REGISTER_SYNC(c, x) \ @@ -56,7 +56,7 @@ NotificationInstance::NotificationInstance() { } NotificationInstance::~NotificationInstance() { - LoggerD("Enter"); + ScopeLogger(); } #define CHECK_EXIST(args, name, out) \ @@ -67,9 +67,9 @@ NotificationInstance::~NotificationInstance() { void NotificationInstance::NotificationManagerPost(const picojson::value& args, picojson::object& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); - LoggerD("Enter"); picojson::value val{picojson::object{}}; PlatformResult status = manager_->Post(args.get(), val.get()); @@ -82,9 +82,9 @@ void NotificationInstance::NotificationManagerPost(const picojson::value& args, void NotificationInstance::NotificationManagerUpdate(const picojson::value& args, picojson::object& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); - LoggerD("Enter"); PlatformResult status = manager_->Update(args.get()); if (status.IsSuccess()) { @@ -96,9 +96,9 @@ void NotificationInstance::NotificationManagerUpdate(const picojson::value& args void NotificationInstance::NotificationManagerRemove(const picojson::value& args, picojson::object& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); - LoggerD("Enter"); PlatformResult status = manager_->Remove(args.get()); if (status.IsSuccess()) { @@ -110,9 +110,9 @@ void NotificationInstance::NotificationManagerRemove(const picojson::value& args void NotificationInstance::NotificationManagerRemoveAll(const picojson::value& args, picojson::object& out) { + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeNotification, &out); - LoggerD("Enter"); PlatformResult status = manager_->RemoveAll(); if (status.IsSuccess()) { @@ -124,7 +124,7 @@ void NotificationInstance::NotificationManagerRemoveAll(const picojson::value& a void NotificationInstance::NotificationManagerGet(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); picojson::value val{picojson::object{}}; PlatformResult status = manager_->Get(args.get(), val.get()); @@ -138,7 +138,7 @@ void NotificationInstance::NotificationManagerGet(const picojson::value& args, void NotificationInstance::NotificationManagerGetAll(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); picojson::value val{picojson::array{}}; PlatformResult status = manager_->GetAll(val.get()); @@ -152,7 +152,7 @@ void NotificationInstance::NotificationManagerGetAll(const picojson::value& args void NotificationInstance::NotificationManagerPlayLEDCustomEffect(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeLED, &out); PlatformResult status = manager_->PlayLEDCustomEffect(args.get()); @@ -166,7 +166,7 @@ void NotificationInstance::NotificationManagerPlayLEDCustomEffect(const picojson void NotificationInstance::NotificationManagerStopLEDCustomEffect(const picojson::value& /*args*/, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeLED, &out); PlatformResult status = manager_->StopLEDCustomEffect(); diff --git a/src/notification/notification_manager.cc b/src/notification/notification_manager.cc index 8af92a8..47cedad 100644 --- a/src/notification/notification_manager.cc +++ b/src/notification/notification_manager.cc @@ -36,31 +36,31 @@ namespace notification { using namespace common; NotificationManager::NotificationManager() { - LoggerD("Enter"); + ScopeLogger(); } NotificationManager::~NotificationManager() { - LoggerD("Enter"); + ScopeLogger(); } NotificationManager* NotificationManager::GetInstance() { - LoggerD("Enter"); + ScopeLogger(); static NotificationManager instance; return &instance; } PlatformResult NotificationManager::Post(const picojson::object& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); return StatusNotification::FromJson(args, false, &out); } PlatformResult NotificationManager::Update(const picojson::object& args) { - LoggerD("Enter"); + ScopeLogger(); return StatusNotification::FromJson(args, true, NULL); } PlatformResult NotificationManager::Remove(const picojson::object& args) { - LoggerD("Enter"); + ScopeLogger(); int id = std::stoi(FromJson(args, "id")); int ret = notification_delete_by_priv_id(NULL, NOTIFICATION_TYPE_NONE, id); @@ -73,7 +73,7 @@ PlatformResult NotificationManager::Remove(const picojson::object& args) { } PlatformResult NotificationManager::RemoveAll() { - LoggerD("Enter"); + ScopeLogger(); int ret = notification_delete_all(NOTIFICATION_TYPE_NOTI); if (ret != NOTIFICATION_ERROR_NONE) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Notification noti remove all failed", @@ -90,7 +90,7 @@ PlatformResult NotificationManager::RemoveAll() { } PlatformResult NotificationManager::Get(const picojson::object& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); int id; try { id = std::stoi(FromJson(args, "id")); @@ -129,7 +129,7 @@ PlatformResult NotificationManager::Get(const picojson::object& args, picojson:: } PlatformResult NotificationManager::GetAll(picojson::array& out) { - LoggerD("Enter"); + ScopeLogger(); notification_h noti = nullptr; notification_list_h noti_list = nullptr; notification_list_h noti_list_iter = nullptr; @@ -192,7 +192,7 @@ PlatformResult NotificationManager::GetAll(picojson::array& out) { } PlatformResult NotificationManager::PlayLEDCustomEffect(const picojson::object& args) { - LoggerD("Enter"); + ScopeLogger(); int timeOn = FromJson(args, "timeOn"); int timeOff = FromJson(args, "timeOff"); @@ -219,7 +219,7 @@ PlatformResult NotificationManager::PlayLEDCustomEffect(const picojson::object& } PlatformResult NotificationManager::StopLEDCustomEffect() { - LoggerD("Enter"); + ScopeLogger(); int ret = device_led_stop_custom(); if (ret != DEVICE_ERROR_NONE) { diff --git a/src/notification/status_notification.cc b/src/notification/status_notification.cc index 3fd3496..d018255 100644 --- a/src/notification/status_notification.cc +++ b/src/notification/status_notification.cc @@ -48,13 +48,15 @@ const ImageEnumMap StatusNotification::thumbnails_map_ = {{0, NOTIFICATION_IMAGE {3, NOTIFICATION_IMAGE_TYPE_LIST_4}}; StatusNotification::StatusNotification() { + ScopeLogger(); } StatusNotification::~StatusNotification() { + ScopeLogger(); } bool StatusNotification::IsColorFormatNumberic(const std::string& color) { - LoggerD("Enter"); + ScopeLogger(); std::string hexCode = "0123456789abcdef"; if (color.length() != 7 || '#' != color[0]) { return false; @@ -71,7 +73,7 @@ bool StatusNotification::IsColorFormatNumberic(const std::string& color) { PlatformResult StatusNotification::SetLayout(notification_h noti_handle, const std::string& noti_type) { - LoggerD("Enter"); + ScopeLogger(); notification_ly_type_e noti_layout = NOTIFICATION_LY_NONE; if (noti_type == "SIMPLE") { @@ -103,7 +105,7 @@ PlatformResult StatusNotification::SetLayout(notification_h noti_handle, } static bool ServiceExtraDataCb(app_control_h service, const char* key, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); if (nullptr == user_data || nullptr == key) { LoggerE("User data or key not exist"); return true; @@ -144,7 +146,7 @@ static bool ServiceExtraDataCb(app_control_h service, const char* key, void* use PlatformResult StatusNotification::Create(notification_type_e noti_type, notification_h* noti_handle) { - LoggerD("Enter"); + ScopeLogger(); *noti_handle = notification_create(noti_type); if (!*noti_handle) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Cannot make new notification object"); @@ -166,7 +168,7 @@ PlatformResult StatusNotification::Create(notification_type_e noti_type, PlatformResult StatusNotification::StatusTypeFromPlatform(notification_type_e noti_type, notification_ly_type_e noti_layout, std::string* type) { - LoggerD("Enter"); + ScopeLogger(); if (noti_type == NOTIFICATION_TYPE_NOTI) { if (noti_layout == NOTIFICATION_LY_NOTI_EVENT_SINGLE || noti_layout == NOTIFICATION_LY_NOTI_EVENT_MULTIPLE) { @@ -189,7 +191,7 @@ PlatformResult StatusNotification::StatusTypeFromPlatform(notification_type_e no PlatformResult StatusNotification::StatusTypeToPlatform(const std::string& type, notification_type_e* noti_type) { - LoggerD("Enter"); + ScopeLogger(); if (type == "SIMPLE" || type == "THUMBNAIL") { *noti_type = NOTIFICATION_TYPE_NOTI; } else if (type == "ONGOING" || type == "PROGRESS") { @@ -205,7 +207,7 @@ PlatformResult StatusNotification::StatusTypeToPlatform(const std::string& type, PlatformResult StatusNotification::GetImage(notification_h noti_handle, notification_image_type_e image_type, std::string* image_path) { - LoggerD("Enter"); + ScopeLogger(); char* path = NULL; *image_path = ""; @@ -224,7 +226,7 @@ PlatformResult StatusNotification::GetImage(notification_h noti_handle, PlatformResult StatusNotification::SetImage(notification_h noti_handle, notification_image_type_e image_type, const std::string& image_path) { - LoggerD("Enter"); + ScopeLogger(); int ret = notification_set_image(noti_handle, image_type, image_path.c_str()); if (ret != NOTIFICATION_ERROR_NONE) { return LogAndCreateResult( @@ -238,7 +240,7 @@ PlatformResult StatusNotification::SetImage(notification_h noti_handle, PlatformResult StatusNotification::GetText(notification_h noti_handle, notification_text_type_e text_type, std::string* noti_text) { - LoggerD("Enter"); + ScopeLogger(); char* text = NULL; *noti_text = ""; @@ -256,7 +258,7 @@ PlatformResult StatusNotification::GetText(notification_h noti_handle, PlatformResult StatusNotification::SetText(notification_h noti_handle, notification_text_type_e text_type, const std::string& noti_text) { - LoggerD("Enter"); + ScopeLogger(); int ret = notification_set_text(noti_handle, text_type, noti_text.c_str(), NULL, NOTIFICATION_VARIABLE_TYPE_NONE); if (ret != NOTIFICATION_ERROR_NONE) { @@ -270,7 +272,7 @@ PlatformResult StatusNotification::SetText(notification_h noti_handle, PlatformResult StatusNotification::GetNumber(notification_h noti_handle, notification_text_type_e text_type, long* number) { - LoggerD("Enter"); + ScopeLogger(); std::string text; PlatformResult status = GetText(noti_handle, text_type, &text); if (status.IsError()) return status; @@ -285,7 +287,7 @@ PlatformResult StatusNotification::GetNumber(notification_h noti_handle, PlatformResult StatusNotification::GetDetailInfos(notification_h noti_handle, picojson::array* out) { - LoggerD("Enter"); + ScopeLogger(); if (info_map_.size() != info_sub_map_.size()) { return LogAndCreateResult(ErrorCode::VALIDATION_ERR, "Different notification information types element size"); @@ -319,7 +321,7 @@ PlatformResult StatusNotification::GetDetailInfos(notification_h noti_handle, PlatformResult StatusNotification::SetDetailInfos(notification_h noti_handle, const picojson::array& value) { - LoggerD("Enter"); + ScopeLogger(); size_t idx = 0; size_t info_map_size = info_map_.size(); @@ -348,7 +350,7 @@ PlatformResult StatusNotification::SetDetailInfos(notification_h noti_handle, } PlatformResult StatusNotification::GetLedColor(notification_h noti_handle, std::string* led_color) { - LoggerD("Enter"); + ScopeLogger(); unsigned int color = 0; notification_led_op_e type = NOTIFICATION_LED_OP_ON; @@ -379,7 +381,7 @@ PlatformResult StatusNotification::GetLedColor(notification_h noti_handle, std:: PlatformResult StatusNotification::SetLedColor(notification_h noti_handle, const std::string& led_color) { - LoggerD("Enter"); + ScopeLogger(); std::string color_str = led_color; std::transform(color_str.begin(), color_str.end(), color_str.begin(), ::tolower); @@ -413,7 +415,7 @@ PlatformResult StatusNotification::SetLedColor(notification_h noti_handle, PlatformResult StatusNotification::GetLedPeriod(notification_h noti_handle, unsigned long* on_period, unsigned long* off_period) { - LoggerD("Enter"); + ScopeLogger(); int on_time = 0; int off_time = 0; @@ -430,7 +432,7 @@ PlatformResult StatusNotification::GetLedPeriod(notification_h noti_handle, PlatformResult StatusNotification::SetLedOnPeriod(notification_h noti_handle, unsigned long on_period) { - LoggerD("Enter"); + ScopeLogger(); unsigned long off_period = 0; PlatformResult status = GetLedPeriod(noti_handle, nullptr, &off_period); if (status.IsError()) return status; @@ -446,7 +448,7 @@ PlatformResult StatusNotification::SetLedOnPeriod(notification_h noti_handle, PlatformResult StatusNotification::SetLedOffPeriod(notification_h noti_handle, unsigned long off_period) { - LoggerD("Enter"); + ScopeLogger(); unsigned long on_period = 0; PlatformResult status = GetLedPeriod(noti_handle, &on_period, nullptr); if (status.IsError()) return status; @@ -461,7 +463,7 @@ PlatformResult StatusNotification::SetLedOffPeriod(notification_h noti_handle, } PlatformResult StatusNotification::GetThumbnails(notification_h noti_handle, picojson::array* out) { - LoggerD("Enter"); + ScopeLogger(); std::string text; size_t thumbnails_map_size = thumbnails_map_.size(); for (size_t idx = 0; idx < thumbnails_map_size; ++idx) { @@ -479,7 +481,7 @@ PlatformResult StatusNotification::GetThumbnails(notification_h noti_handle, pic PlatformResult StatusNotification::SetThumbnails(notification_h noti_handle, const picojson::array& value) { - LoggerD("Enter"); + ScopeLogger(); size_t idx = 0; size_t thumbnails_map_size = thumbnails_map_.size(); @@ -503,7 +505,7 @@ PlatformResult StatusNotification::SetThumbnails(notification_h noti_handle, PlatformResult StatusNotification::GetSoundPath(notification_h noti_handle, std::string* sound_path) { - LoggerD("Enter"); + ScopeLogger(); *sound_path = ""; const char* path = NULL; @@ -526,7 +528,7 @@ PlatformResult StatusNotification::GetSoundPath(notification_h noti_handle, PlatformResult StatusNotification::SetSoundPath(notification_h noti_handle, const std::string& sound_path) { - LoggerD("Enter"); + ScopeLogger(); int ret = notification_set_sound(noti_handle, NOTIFICATION_SOUND_TYPE_USER_DATA, sound_path.c_str()); if (ret != NOTIFICATION_ERROR_NONE) { @@ -540,7 +542,7 @@ PlatformResult StatusNotification::SetSoundPath(notification_h noti_handle, } PlatformResult StatusNotification::GetVibration(notification_h noti_handle, bool* vibration) { - LoggerD("Enter"); + ScopeLogger(); notification_vibration_type_e vib_type = NOTIFICATION_VIBRATION_TYPE_NONE; if (notification_get_vibration(noti_handle, &vib_type, NULL) != NOTIFICATION_ERROR_NONE) { @@ -558,7 +560,7 @@ PlatformResult StatusNotification::GetVibration(notification_h noti_handle, bool } PlatformResult StatusNotification::SetVibration(notification_h noti_handle, bool vibration) { - LoggerD("Enter"); + ScopeLogger(); bool platform_vibration; PlatformResult status = GetVibration(noti_handle, &platform_vibration); if (status.IsError()) return status; @@ -582,7 +584,7 @@ PlatformResult StatusNotification::SetVibration(notification_h noti_handle, bool PlatformResult StatusNotification::GetApplicationControl(app_control_h app_handle, picojson::object* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); picojson::object& out = *out_ptr; char* operation = NULL; @@ -642,7 +644,7 @@ PlatformResult StatusNotification::GetApplicationControl(app_control_h app_handl PlatformResult StatusNotification::SetApplicationControl(app_control_h app_handle, const picojson::object& app_ctrl) { - LoggerD("Enter"); + ScopeLogger(); picojson::value val(app_ctrl); const std::string& operation = common::FromJson(app_ctrl, "operation"); @@ -716,7 +718,7 @@ PlatformResult StatusNotification::SetApplicationControl(app_control_h app_handl } PlatformResult StatusNotification::GetApplicationId(app_control_h app_handle, std::string* app_id) { - LoggerD("Enter"); + ScopeLogger(); char* app_id_str = NULL; SCOPE_EXIT { free(app_id_str); @@ -739,7 +741,7 @@ PlatformResult StatusNotification::GetApplicationId(app_control_h app_handle, st PlatformResult StatusNotification::SetApplicationId(app_control_h app_handle, const std::string& app_id) { - LoggerD("Enter"); + ScopeLogger(); int ret = app_control_set_app_id(app_handle, app_id.c_str()); if (ret != APP_CONTROL_ERROR_NONE) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Set applicaiton ID error", @@ -754,7 +756,7 @@ PlatformResult StatusNotification::SetApplicationId(app_control_h app_handle, PlatformResult StatusNotification::GetProgressValue(notification_h noti_handle, const std::string& progess_type, double* progress_value) { - LoggerD("Enter"); + ScopeLogger(); double tmp_progress_value = 0.0; if (progess_type == kProgressTypeByte) { @@ -781,7 +783,7 @@ PlatformResult StatusNotification::GetProgressValue(notification_h noti_handle, PlatformResult StatusNotification::SetProgressValue(notification_h noti_handle, const std::string& progress_type, double progress_value, bool is_update) { - LoggerD("Enter"); + ScopeLogger(); int ret; if (progress_type == kProgressTypeByte) { @@ -811,7 +813,7 @@ PlatformResult StatusNotification::SetProgressValue(notification_h noti_handle, } PlatformResult StatusNotification::GetPostedTime(notification_h noti_handle, time_t* posted_time) { - LoggerD("Enter"); + ScopeLogger(); *posted_time = 0; if (notification_get_insert_time(noti_handle, posted_time) != NOTIFICATION_ERROR_NONE) { @@ -822,7 +824,7 @@ PlatformResult StatusNotification::GetPostedTime(notification_h noti_handle, tim } PlatformResult StatusNotification::GetNotiHandle(int id, notification_h* noti_handle) { - LoggerD("Enter"); + ScopeLogger(); *noti_handle = notification_load(NULL, id); if (NULL == *noti_handle) { return LogAndCreateResult(ErrorCode::NOT_FOUND_ERR, "Not found or removed notification id"); @@ -833,7 +835,7 @@ PlatformResult StatusNotification::GetNotiHandle(int id, notification_h* noti_ha PlatformResult StatusNotification::GetAppControl(notification_h noti_handle, app_control_h* app_control) { - LoggerD("Enter"); + ScopeLogger(); int ret = notification_get_launch_option(noti_handle, NOTIFICATION_LAUNCH_OPTION_APP_CONTROL, static_cast(app_control)); if (ret != NOTIFICATION_ERROR_NONE) { @@ -845,7 +847,7 @@ PlatformResult StatusNotification::GetAppControl(notification_h noti_handle, } PlatformResult StatusNotification::CreateAppControl(app_control_h* app_control) { - LoggerD("Enter"); + ScopeLogger(); int ret = app_control_create(app_control); if (ret != APP_CONTROL_ERROR_NONE) { return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "Application create error", @@ -857,7 +859,7 @@ PlatformResult StatusNotification::CreateAppControl(app_control_h* app_control) PlatformResult StatusNotification::SetAppControl(notification_h noti_handle, app_control_h app_control) { - LoggerD("Enter"); + ScopeLogger(); int ret = notification_set_launch_option(noti_handle, NOTIFICATION_LAUNCH_OPTION_APP_CONTROL, static_cast(app_control)); if (ret != APP_CONTROL_ERROR_NONE) { @@ -870,7 +872,7 @@ PlatformResult StatusNotification::SetAppControl(notification_h noti_handle, PlatformResult StatusNotification::ToJson(int id, notification_h noti_handle, app_control_h app_handle, picojson::object* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); picojson::object& out = *out_ptr; out["id"] = picojson::value(std::to_string(id)); @@ -1013,7 +1015,7 @@ PlatformResult StatusNotification::ToJson(int id, notification_h noti_handle, PlatformResult StatusNotification::FromJson(const picojson::object& args, bool is_update, picojson::object* out_ptr) { - LoggerD("Enter"); + ScopeLogger(); picojson::object noti_obj = common::FromJson(args, "notification"); const std::string& status_type = common::FromJson(noti_obj, "statusType"); diff --git a/src/package/package_extension.cc b/src/package/package_extension.cc index ecdd434..f8dae54 100644 --- a/src/package/package_extension.cc +++ b/src/package/package_extension.cc @@ -23,21 +23,21 @@ extern const char kSource_package_api[]; common::Extension* CreateExtension() { - LoggerD("Enter"); + ScopeLogger(); return new PackageExtension; } PackageExtension::PackageExtension() { - LoggerD("Enter"); + ScopeLogger(); SetExtensionName("tizen.package"); SetJavaScriptAPI(kSource_package_api); } PackageExtension::~PackageExtension() { - LoggerD("Enter"); + ScopeLogger(); } common::Instance* PackageExtension::CreateInstance() { - LoggerD("Enter"); + ScopeLogger(); return new extension::package::PackageInstance; } diff --git a/src/package/package_info_provider.cc b/src/package/package_info_provider.cc index f89fc09..e478cdc 100644 --- a/src/package/package_info_provider.cc +++ b/src/package/package_info_provider.cc @@ -46,7 +46,7 @@ using common::tools::ReportSuccess; out["error"] = exception.ToJSON(); static int PackageInfoGetListCb(const pkgmgrinfo_pkginfo_h info, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::array* array_data = static_cast(user_data); if (!array_data) { @@ -63,7 +63,7 @@ static int PackageInfoGetListCb(const pkgmgrinfo_pkginfo_h info, void* user_data } void PackageInfoProvider::GetPackagesInfo(picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); clock_t start_time, end_time; start_time = clock(); @@ -86,7 +86,7 @@ void PackageInfoProvider::GetPackagesInfo(picojson::object& out) { } void PackageInfoProvider::GetPackageInfo(picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); char* package_id = NULL; if (GetCurrentPackageId(&package_id)) { @@ -99,7 +99,7 @@ void PackageInfoProvider::GetPackageInfo(picojson::object& out) { } void PackageInfoProvider::GetPackageInfo(const char* package_id, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); if (strlen(package_id) <= 0) { LoggerE("Wrong Package ID"); @@ -129,7 +129,7 @@ void PackageInfoProvider::GetPackageInfo(const char* package_id, picojson::objec static bool PackageAppInfoCb(package_info_app_component_type_e comp_type, const char* app_id, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::array* array_data = static_cast(user_data); if (!array_data) { @@ -143,6 +143,7 @@ static bool PackageAppInfoCb(package_info_app_component_type_e comp_type, const bool PackageInfoProvider::ConvertToPackageToObject(const pkgmgrinfo_pkginfo_h info, picojson::object& out) { + ScopeLogger(); int ret = 0; char* id = NULL; @@ -231,7 +232,7 @@ bool PackageInfoProvider::ConvertToPackageToObject(const pkgmgrinfo_pkginfo_h in namespace { void GetSize(const std::string& id, int service_mode, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); pkgmgr_client* pc = pkgmgr_client_new(PC_REQUEST); int size = pkgmgr_client_usr_request_service(PM_REQUEST_GET_SIZE, service_mode, pc, NULL, id.c_str(), getuid(), NULL, NULL, NULL); @@ -248,17 +249,17 @@ void GetSize(const std::string& id, int service_mode, picojson::object* out) { } // namespace void PackageInfoProvider::GetTotalSize(const std::string& id, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); GetSize(id, PM_GET_TOTAL_SIZE, out); } void PackageInfoProvider::GetDataSize(const std::string& id, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); GetSize(id, PM_GET_DATA_SIZE, out); } bool PackageInfoProvider::GetCurrentPackageId(char** package_id) { - LoggerD("Enter"); + ScopeLogger(); int ret = 0; char* app_id = NULL; diff --git a/src/package/package_instance.cc b/src/package/package_instance.cc index 4467ae6..0bf31f7 100644 --- a/src/package/package_instance.cc +++ b/src/package/package_instance.cc @@ -52,6 +52,7 @@ typedef enum _PackageThreadWorkType { class PackageUserData { public: PackageUserData(PackageInstance* ins, int id, PackageThreadWorkType task) { + ScopeLogger(); instance_ = ins; callback_id_ = id; work_ = task; @@ -65,7 +66,7 @@ class PackageUserData { typedef std::shared_ptr PackageUserDataPtr; static void* PackageThreadWork(const PackageUserDataPtr& userData) { - LoggerD("Enter"); + ScopeLogger(); switch (userData->work_) { case PackageThreadWorkGetPackagesInfo: { @@ -81,7 +82,7 @@ static void* PackageThreadWork(const PackageUserDataPtr& userData) { } static gboolean PackageAfterWork(const PackageUserDataPtr& userData) { - LoggerD("Enter"); + ScopeLogger(); userData->data_["callbackId"] = picojson::value(static_cast(userData->callback_id_)); picojson::value result = picojson::value(userData->data_); @@ -94,7 +95,7 @@ static void PackageRequestCb(int id, const char* type, const char* package, package_manager_event_type_e event_type, package_manager_event_state_e event_state, int progress, package_manager_error_e error, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); PackageInstance* instance = static_cast(user_data); if (!instance) { @@ -135,7 +136,7 @@ static void PackageListenerCb(const char* type, const char* package, package_manager_event_type_e event_type, package_manager_event_state_e event_state, int progress, package_manager_error_e error, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); PackageInstance* instance = static_cast(user_data); if (!instance) { @@ -178,6 +179,7 @@ static void PackageListenerCb(const char* type, const char* package, } static std::string ltrim(const std::string& s) { + ScopeLogger(); std::string str = s; std::string::iterator i; for (i = str.begin(); i != str.end(); ++i) { @@ -194,6 +196,7 @@ static std::string ltrim(const std::string& s) { } static std::string convertUriToPath(const std::string& uri) { + ScopeLogger(); std::string result; std::string schema("file://"); std::string str = ltrim(uri); @@ -209,7 +212,7 @@ static std::string convertUriToPath(const std::string& uri) { } PackageInstance::PackageInstance() { - LoggerD("Enter"); + ScopeLogger(); int ret = package_manager_request_create(&request_); if (ret != PACKAGE_MANAGER_ERROR_NONE) { @@ -250,7 +253,7 @@ PackageInstance::PackageInstance() { } PackageInstance::~PackageInstance() { - LoggerD("Enter"); + ScopeLogger(); package_manager_request_unset_event_cb(request_); package_manager_request_destroy(request_); package_manager_destroy(manager_); @@ -263,17 +266,17 @@ PackageInstance::~PackageInstance() { } void PackageInstance::RegisterCallback(int request_id, int callback_id) { - LoggerD("Enter"); + ScopeLogger(); callbacks_map_[request_id] = callback_id; } void PackageInstance::DeregisterCallback(int request_id) { - LoggerD("Enter"); + ScopeLogger(); callbacks_map_.erase(request_id); } void PackageInstance::InvokeCallback(int request_id, picojson::object& param) { - LoggerD("Enter"); + ScopeLogger(); int callback_id = callbacks_map_[request_id]; @@ -283,7 +286,7 @@ void PackageInstance::InvokeCallback(int request_id, picojson::object& param) { } void PackageInstance::PackageManagerInstall(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInstall, &out); @@ -323,7 +326,7 @@ void PackageInstance::PackageManagerInstall(const picojson::value& args, picojso } void PackageInstance::PackageManagerUninstall(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInstall, &out); @@ -373,7 +376,7 @@ void PackageInstance::PackageManagerUninstall(const picojson::value& args, picoj } void PackageInstance::PackageManagerGetpackagesinfo(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInfo, &out); @@ -387,7 +390,7 @@ void PackageInstance::PackageManagerGetpackagesinfo(const picojson::value& args, } void PackageInstance::PackageManagerGetpackageinfo(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInfo, &out); @@ -401,7 +404,7 @@ void PackageInstance::PackageManagerGetpackageinfo(const picojson::value& args, void PackageInstance::PackageManagerGetTotalSize(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); const auto& id = args.get("id"); @@ -414,7 +417,7 @@ void PackageInstance::PackageManagerGetTotalSize(const picojson::value& args, void PackageInstance::PackageManagerGetDataSize(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); const auto& id = args.get("id"); @@ -426,14 +429,14 @@ void PackageInstance::PackageManagerGetDataSize(const picojson::value& args, } void PackageInstance::InvokeListener(picojson::object& param) { - LoggerD("Enter"); + ScopeLogger(); picojson::value result = picojson::value(param); Instance::PostMessage(this, result.serialize().c_str()); } void PackageInstance::PackageManagerSetpackageinfoeventlistener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInfo, &out); @@ -466,7 +469,7 @@ void PackageInstance::PackageManagerSetpackageinfoeventlistener(const picojson:: void PackageInstance::PackageManagerUnsetpackageinfoeventlistener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePackageInfo, &out); @@ -497,7 +500,7 @@ void PackageInstance::PackageManagerUnsetpackageinfoeventlistener(const picojson } void PackageInstance::InvokeErrorCallbackAsync(int callback_id, const PlatformException& ex) { - LoggerD("Enter"); + ScopeLogger(); picojson::object param; LogAndReportError(ex, param); diff --git a/src/power/power_extension.cc b/src/power/power_extension.cc index 6f7d3af..c027071 100644 --- a/src/power/power_extension.cc +++ b/src/power/power_extension.cc @@ -26,11 +26,13 @@ common::Extension* CreateExtension() { } PowerExtension::PowerExtension() { + ScopeLogger(); SetExtensionName("tizen.power"); SetJavaScriptAPI(kSource_power_api); } PowerExtension::~PowerExtension() { + ScopeLogger(); } common::Instance* PowerExtension::CreateInstance() { diff --git a/src/power/power_instance.cc b/src/power/power_instance.cc index 8027ba1..b1e6968 100644 --- a/src/power/power_instance.cc +++ b/src/power/power_instance.cc @@ -51,7 +51,7 @@ using namespace common; using namespace extension::power; PowerInstance::PowerInstance() { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -69,7 +69,7 @@ PowerInstance::PowerInstance() { } PowerInstance::~PowerInstance() { - LoggerD("Enter"); + ScopeLogger(); PowerManager::GetInstance()->RemoveListener(this); @@ -99,7 +99,7 @@ enum PowerCallbacks { } void PowerInstance::PowerManagerRequest(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePower, &out); const std::string& resource = args.get("resource").get(); @@ -114,7 +114,7 @@ void PowerInstance::PowerManagerRequest(const picojson::value& args, picojson::o } void PowerInstance::PowerManagerRelease(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); const std::string& resource = args.get("resource").get(); PlatformResult result = PowerManager::GetInstance()->Release(kPowerResourceMap.at(resource)); if (result.IsError()) @@ -125,7 +125,7 @@ void PowerInstance::PowerManagerRelease(const picojson::value& args, picojson::o void PowerInstance::PowerManagerGetscreenbrightness(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); double brightness; PlatformResult result = PowerManager::GetInstance()->GetScreenBrightness(&brightness); if (result.IsError()) @@ -136,7 +136,7 @@ void PowerInstance::PowerManagerGetscreenbrightness(const picojson::value& args, void PowerInstance::PowerManagerSetscreenbrightness(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePower, &out); CHECK_EXIST(args, "brightness", out) @@ -150,7 +150,7 @@ void PowerInstance::PowerManagerSetscreenbrightness(const picojson::value& args, } void PowerInstance::PowerManagerIsscreenon(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); bool state = false; PlatformResult result = PowerManager::GetInstance()->IsScreenOn(&state); if (result.IsError()) @@ -161,7 +161,7 @@ void PowerInstance::PowerManagerIsscreenon(const picojson::value& args, picojson void PowerInstance::PowerManagerRestorescreenbrightness(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult result = PowerManager::GetInstance()->RestoreScreenBrightness(); if (result.IsError()) LogAndReportError(result, &out); @@ -170,7 +170,7 @@ void PowerInstance::PowerManagerRestorescreenbrightness(const picojson::value& a } void PowerInstance::PowerManagerTurnscreenon(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); LoggerW( "DEPRECATION WARNING: turnScreenOn() is deprecated and will be removed from next release. " "Use request() instead."); @@ -185,7 +185,7 @@ void PowerInstance::PowerManagerTurnscreenon(const picojson::value& args, picojs } void PowerInstance::PowerManagerTurnscreenoff(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); LoggerW( "DEPRECATION WARNING: turnScreenOff() is deprecated and will be removed from next release. " "Use release() instead."); @@ -200,7 +200,7 @@ void PowerInstance::PowerManagerTurnscreenoff(const picojson::value& args, picoj } void PowerInstance::OnScreenStateChanged(PowerState prev_state, PowerState new_state) { - LoggerD("Enter"); + ScopeLogger(); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); obj["cmd"] = picojson::value("ScreenStateChanged"); diff --git a/src/power/power_manager.cc b/src/power/power_manager.cc index 946b600..cf50a59 100644 --- a/src/power/power_manager.cc +++ b/src/power/power_manager.cc @@ -42,7 +42,7 @@ PowerManager::PowerManager() should_be_read_from_cache_(false), set_custom_brightness_(false), current_requested_state_(POWER_STATE_NONE) { - LoggerD("Enter"); + ScopeLogger(); display_state_e platform_state = DISPLAY_STATE_NORMAL; int ret = device_display_get_state(&platform_state); @@ -69,20 +69,20 @@ PowerManager::PowerManager() } PowerManager::~PowerManager() { - LoggerD("Enter"); + ScopeLogger(); int ret = device_remove_callback(DEVICE_CALLBACK_DISPLAY_STATE, PowerManager::OnPlatformStateChangedCB); if (DEVICE_ERROR_NONE != ret) LoggerE("device_remove_callback failed (%d)", ret); } PowerManager* PowerManager::GetInstance() { - LoggerD("Enter"); + ScopeLogger(); static PowerManager instance; return &instance; } void PowerManager::OnPlatformStateChangedCB(device_callback_e type, void* value, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); PowerManager* object = static_cast(user_data); if (object == NULL) { LoggerE("User data is NULL"); @@ -127,18 +127,18 @@ void PowerManager::OnPlatformStateChangedCB(device_callback_e type, void* value, } void PowerManager::AddListener(PowerManagerListener* listener) { - LoggerD("Enter"); + ScopeLogger(); auto it = std::find(listeners_.begin(), listeners_.end(), listener); if (it == listeners_.end()) listeners_.push_back(listener); } void PowerManager::RemoveListener(PowerManagerListener* listener) { - LoggerD("Enter"); + ScopeLogger(); listeners_.remove(listener); } PlatformResult PowerManager::Request(PowerResource resource, PowerState state) { - LoggerD("Enter"); + ScopeLogger(); if (resource == POWER_RESOURCE_SCREEN && state == POWER_STATE_CPU_AWAKE) return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "invalid PowerState"); if (resource == POWER_RESOURCE_CPU && state != POWER_STATE_CPU_AWAKE) @@ -236,7 +236,7 @@ PlatformResult PowerManager::Request(PowerResource resource, PowerState state) { } PlatformResult PowerManager::Release(PowerResource resource) { - LoggerD("Enter"); + ScopeLogger(); int ret; if (POWER_RESOURCE_SCREEN == resource) { ret = device_power_release_lock(POWER_LOCK_DISPLAY); @@ -280,7 +280,7 @@ PlatformResult PowerManager::Release(PowerResource resource) { } PlatformResult PowerManager::GetScreenBrightness(double* output) { - LoggerD("Enter"); + ScopeLogger(); int brightness = 0; auto error_code = GetPlatformBrightness(&brightness); @@ -303,7 +303,7 @@ PlatformResult PowerManager::GetScreenBrightness(double* output) { } PlatformResult PowerManager::SetScreenBrightness(double brightness) { - LoggerD("Enter"); + ScopeLogger(); if (brightness > 1 || brightness < 0) return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, "brightness should be 0 <= brightness <= 1"); @@ -325,7 +325,7 @@ PlatformResult PowerManager::SetScreenBrightness(double brightness) { } PlatformResult PowerManager::IsScreenOn(bool* state) { - LoggerD("Enter"); + ScopeLogger(); display_state_e platform_state = DISPLAY_STATE_NORMAL; int ret = device_display_get_state(&platform_state); @@ -339,7 +339,7 @@ PlatformResult PowerManager::IsScreenOn(bool* state) { } PlatformResult PowerManager::SetScreenState(bool onoff) { - LoggerD("Enter"); + ScopeLogger(); int ret = device_display_change_state(onoff ? DISPLAY_STATE_NORMAL : DISPLAY_STATE_SCREEN_OFF); if (DEVICE_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Platform error while changing screen state", @@ -366,7 +366,7 @@ PlatformResult PowerManager::SetScreenState(bool onoff) { } PlatformResult PowerManager::RestoreScreenBrightness() { - LoggerD("Enter"); + ScopeLogger(); int result = 0; auto error_code = PowerPlatformProxy::GetInstance().SetBrightnessFromSettings(&result); if (!error_code || DEVICE_ERROR_NONE != result) { @@ -377,7 +377,7 @@ PlatformResult PowerManager::RestoreScreenBrightness() { } PlatformResult PowerManager::SetPlatformBrightness(int brightness) { - LoggerD("Enter"); + ScopeLogger(); if (current_state_ == POWER_STATE_SCREEN_DIM) { current_brightness_ = brightness; LoggerD("Current state is not normal state the value is saved in cache: %d", brightness); @@ -408,7 +408,7 @@ PlatformResult PowerManager::SetPlatformBrightness(int brightness) { } PlatformResult PowerManager::GetPlatformBrightness(int* result) { - LoggerD("Entered"); + ScopeLogger(); int brightness = 0; @@ -454,7 +454,7 @@ PlatformResult PowerManager::GetPlatformBrightness(int* result) { } PlatformResult PowerManager::RestoreSettedBrightness() { - LoggerD("Enter"); + ScopeLogger(); PlatformResult result(ErrorCode::NO_ERROR); int is_custom_mode = 0; vconf_get_int(VCONFKEY_PM_CUSTOM_BRIGHTNESS_STATUS, &is_custom_mode); @@ -471,7 +471,7 @@ PlatformResult PowerManager::RestoreSettedBrightness() { } void PowerManager::BroadcastScreenState(PowerState current) { - LoggerD("Enter"); + ScopeLogger(); if (current_state_ == current) return; PowerState prev_state = current_state_; diff --git a/src/power/power_platform_proxy.cc b/src/power/power_platform_proxy.cc index f23f4a0..5947805 100644 --- a/src/power/power_platform_proxy.cc +++ b/src/power/power_platform_proxy.cc @@ -28,21 +28,21 @@ namespace power { PowerPlatformProxy::PowerPlatformProxy() : gdbus_op_(common::gdbus::GDBusPowerWrapper::kDefaultBusName, common::gdbus::GDBusPowerWrapper::kDefaultObjectPath) { - LoggerD("Entered"); + ScopeLogger(); } PowerPlatformProxy::~PowerPlatformProxy() { - LoggerD("Entered"); + ScopeLogger(); } PowerPlatformProxy& PowerPlatformProxy::GetInstance() { - LoggerD("Entered"); + ScopeLogger(); static PowerPlatformProxy instance; return instance; } common::PlatformResult PowerPlatformProxy::LockState(int* result) { - LoggerD("Entered PPP LockState"); + ScopeLogger(); if (!gdbus_op_.LockState(result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); @@ -51,7 +51,7 @@ common::PlatformResult PowerPlatformProxy::LockState(int* result) { } common::PlatformResult PowerPlatformProxy::UnlockState(int* result) { - LoggerD("Entered PPP UnlockState"); + ScopeLogger(); if (!gdbus_op_.UnlockState(result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); @@ -60,7 +60,7 @@ common::PlatformResult PowerPlatformProxy::UnlockState(int* result) { } common::PlatformResult PowerPlatformProxy::SetBrightnessFromSettings(int* result) { - LoggerD("Entered PPP SetBrightnessFromSettings"); + ScopeLogger(); if (!gdbus_op_.ReleaseBrightness(result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); @@ -69,7 +69,7 @@ common::PlatformResult PowerPlatformProxy::SetBrightnessFromSettings(int* result } common::PlatformResult PowerPlatformProxy::SetBrightness(int val, int* result) { - LoggerD("Entered PPP SetBrightness"); + ScopeLogger(); if (!gdbus_op_.HoldBrightness(val, result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); @@ -78,7 +78,7 @@ common::PlatformResult PowerPlatformProxy::SetBrightness(int val, int* result) { } common::PlatformResult PowerPlatformProxy::GetBrightness(int* result) { - LoggerD("Entered PPP GetBrightness"); + ScopeLogger(); if (!gdbus_op_.CurrentBrightness(result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); @@ -87,7 +87,7 @@ common::PlatformResult PowerPlatformProxy::GetBrightness(int* result) { } common::PlatformResult PowerPlatformProxy::IsCustomBrightness(int* result) { - LoggerD("Entered PPP IsCustomBrightness"); + ScopeLogger(); if (!gdbus_op_.CustomBrightness(result)) { LoggerE("%s", gdbus_op_.GetLastError().c_str()); return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get reply from gdbus"); diff --git a/src/preference/preference_instance.cc b/src/preference/preference_instance.cc index c7ebe80..f7a24a6 100644 --- a/src/preference/preference_instance.cc +++ b/src/preference/preference_instance.cc @@ -114,6 +114,7 @@ common::TizenResult PreferenceInstance::SetChangeListener(const picojson::object const auto& key = args.find(kKey)->second.get(); common::PostCallback callback = [this](const common::TizenResult&, const picojson::value& v) { + ScopeLogger("Entered into asynchronous function, callback"); Post(kPreferenceChangeListenerToken, common::TizenSuccess{v}); }; diff --git a/src/preference/preference_manager.cc b/src/preference/preference_manager.cc index b00b317..ecd9665 100644 --- a/src/preference/preference_manager.cc +++ b/src/preference/preference_manager.cc @@ -33,6 +33,7 @@ const char* kKey = "key"; const char* kValue = "value"; common::TizenResult MakeErrResult(int ret, const char* err_msg) { + ScopeLogger(); LoggerE("%s", err_msg); switch (ret) { case PREFERENCE_ERROR_INVALID_PARAMETER: @@ -53,6 +54,7 @@ common::TizenResult MakeErrResult(int ret, const char* err_msg) { } int GetValueInternal(const std::string& key, picojson::value* val) { + ScopeLogger(); char* result_str = nullptr; int ret = preference_get_string(key.c_str(), &result_str); @@ -156,6 +158,7 @@ common::TizenResult PreferenceManager::GetAll(const common::PostCallback& callba ScopeLogger(); auto get_all = [](const common::PostCallback& callback) -> void { + ScopeLogger("Entered into asynchronous function, get_all"); picojson::value response{picojson::array{}}; auto* array = &response.get(); diff --git a/src/push/push_instance.cc b/src/push/push_instance.cc index bc321f9..f7b277d 100644 --- a/src/push/push_instance.cc +++ b/src/push/push_instance.cc @@ -31,7 +31,7 @@ const std::string kPrivilegePush = "http://tizen.org/privilege/push"; } // namespace PushInstance::PushInstance() { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -63,7 +63,7 @@ PushInstance::PushInstance() { } void PushInstance::registerService(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); common::PlatformResult result = impl->registerService(args.get("callbackId").get()); @@ -75,7 +75,7 @@ void PushInstance::registerService(const picojson::value& args, picojson::object } void PushInstance::registerApplication(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); common::PlatformResult result = impl->registerApplication(args.get("callbackId").get()); @@ -87,7 +87,7 @@ void PushInstance::registerApplication(const picojson::value& args, picojson::ob } void PushInstance::unregisterService(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); @@ -100,7 +100,7 @@ void PushInstance::unregisterService(const picojson::value& args, picojson::obje } void PushInstance::unregisterApplication(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); @@ -113,7 +113,7 @@ void PushInstance::unregisterApplication(const picojson::value& args, picojson:: } void PushInstance::connectService(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); @@ -126,7 +126,7 @@ void PushInstance::connectService(const picojson::value& args, picojson::object& } void PushInstance::connect(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); @@ -139,7 +139,7 @@ void PushInstance::connect(const picojson::value& args, picojson::object& out) { } void PushInstance::disconnectService(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); @@ -152,7 +152,7 @@ void PushInstance::disconnectService(const picojson::value& args, picojson::obje } void PushInstance::disconnect(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); @@ -165,7 +165,7 @@ void PushInstance::disconnect(const picojson::value& args, picojson::object& out } void PushInstance::getRegistrationId(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); @@ -182,7 +182,7 @@ void PushInstance::getRegistrationId(const picojson::value& args, picojson::obje } void PushInstance::getUnreadNotifications(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); @@ -195,7 +195,7 @@ void PushInstance::getUnreadNotifications(const picojson::value& args, picojson: } void PushInstance::getPushMessage(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegePush, &out); @@ -211,7 +211,7 @@ void PushInstance::getPushMessage(const picojson::value& args, picojson::object& } void PushInstance::onPushState(push_service_state_e state, common::PlatformResult result) { - LoggerD("Enter"); + ScopeLogger(); picojson::value res{picojson::object()}; picojson::object& dict = res.get(); @@ -226,6 +226,7 @@ void PushInstance::onPushState(push_service_state_e state, common::PlatformResul void PushInstance::onPushRegister(double callbackId, common::PlatformResult result, const std::string& id) { + ScopeLogger(); picojson::value res{picojson::object()}; picojson::object& dict = res.get(); @@ -239,7 +240,7 @@ void PushInstance::onPushRegister(double callbackId, common::PlatformResult resu } void PushInstance::onPushNotify(push_service_notification_h noti) { - LoggerD("Enter"); + ScopeLogger(); picojson::value res{picojson::object()}; picojson::object& dict = res.get(); @@ -254,7 +255,7 @@ void PushInstance::onPushNotify(push_service_notification_h noti) { } void PushInstance::onDeregister(double callbackId, common::PlatformResult result) { - LoggerD("Enter"); + ScopeLogger(); picojson::value res{picojson::object()}; picojson::object& dict = res.get(); @@ -266,7 +267,7 @@ void PushInstance::onDeregister(double callbackId, common::PlatformResult result } PushInstance::~PushInstance() { - LoggerD("Enter"); + ScopeLogger(); if (impl) { delete impl; impl = nullptr; diff --git a/src/push/push_manager.cc b/src/push/push_manager.cc index 3851c4c..7d669ef 100644 --- a/src/push/push_manager.cc +++ b/src/push/push_manager.cc @@ -54,13 +54,13 @@ PushManager::PushManager(EventListener* listener) app_control_(nullptr), operation_(nullptr), m_ignoreNotificationEvents(true) { - LoggerD("Enter"); + ScopeLogger(); initPkgId(); InitAppControl(); } PushManager::~PushManager() { - LoggerD("Enter"); + ScopeLogger(); m_listener = nullptr; if (m_handle) { @@ -78,7 +78,7 @@ PushManager::~PushManager() { } void PushManager::initPkgId() { - LoggerD("Enter"); + ScopeLogger(); int pid = getpid(); char* temp = nullptr; int ret = app_manager_get_app_id(pid, &temp); @@ -109,7 +109,7 @@ void PushManager::initPkgId() { } void PushManager::InitAppControl() { - LoggerD("Enter"); + ScopeLogger(); const auto encoded_bundle = PushManagerCommon::GetEncodedBundle(); @@ -133,7 +133,7 @@ void PushManager::InitAppControl() { } bool PushManager::checkRegistered_2_4() { - LoggerD("Enter"); + ScopeLogger(); bool result = false; char* temp = NULL; int ret = push_service_get_registration_id(m_handle, &temp); @@ -146,14 +146,14 @@ bool PushManager::checkRegistered_2_4() { } PlatformResult PushManager::connectService() { - LoggerD("Enter"); + ScopeLogger(); CHECK_CONNECTION(); m_ignoreNotificationEvents = false; return common::PlatformResult(ErrorCode::NO_ERROR); } PlatformResult PushManager::connect() { - LoggerD("Enter"); + ScopeLogger(); if (!m_handle) { int ret = push_service_connect(m_pkgId.c_str(), onPushState, onPushNotify, this, &m_handle); @@ -167,7 +167,7 @@ PlatformResult PushManager::connect() { } PlatformResult PushManager::disconnectService() { - LoggerD("Enter"); + ScopeLogger(); // disconnecting from push server if (m_handle) { push_service_disconnect(m_handle); @@ -178,7 +178,7 @@ PlatformResult PushManager::disconnectService() { } PlatformResult PushManager::disconnect() { - LoggerD("Enter"); + ScopeLogger(); if (m_handle) { push_service_disconnect(m_handle); m_handle = nullptr; @@ -187,7 +187,7 @@ PlatformResult PushManager::disconnect() { } PlatformResult PushManager::registerService(double callbackId) { - LoggerD("Enter"); + ScopeLogger(); CHECK_CONNECTION(); PushManagerHolder* holder = new PushManagerHolder{this, callbackId}; @@ -203,7 +203,7 @@ PlatformResult PushManager::registerService(double callbackId) { } PlatformResult PushManager::registerApplication(double callbackId) { - LoggerD("Enter"); + ScopeLogger(); PushManagerHolder* holder = new PushManagerHolder{this, callbackId}; @@ -218,7 +218,7 @@ PlatformResult PushManager::registerApplication(double callbackId) { } common::PlatformResult PushManager::unregisterService(double callbackId) { - LoggerD("Enter"); + ScopeLogger(); CHECK_CONNECTION(); PushManagerHolder* holder = new PushManagerHolder{this, callbackId}; @@ -249,7 +249,7 @@ common::PlatformResult PushManager::unregisterService(double callbackId) { } common::PlatformResult PushManager::unregisterApplication(double callbackId) { - LoggerD("Enter"); + ScopeLogger(); PushManagerHolder* holder = new PushManagerHolder{this, callbackId}; int ret = push_service_deregister(m_handle, onDeregister, holder); @@ -263,7 +263,7 @@ common::PlatformResult PushManager::unregisterApplication(double callbackId) { } common::PlatformResult PushManager::getRegistrationId(std::string& id) { - LoggerD("Enter"); + ScopeLogger(); char* temp = nullptr; int ret = push_service_get_registration_id(m_handle, &temp); if (PUSH_SERVICE_ERROR_NONE != ret) { @@ -277,7 +277,7 @@ common::PlatformResult PushManager::getRegistrationId(std::string& id) { } common::PlatformResult PushManager::getUnreadNotifications() { - LoggerD("Enter"); + ScopeLogger(); if (!m_handle) { return LogAndCreateResult(ErrorCode::SERVICE_NOT_AVAILABLE_ERR, "Not connected with push service"); @@ -293,7 +293,7 @@ common::PlatformResult PushManager::getUnreadNotifications() { } PlatformResult PushManager::getPushMessage(picojson::value* out) { - LoggerD("Enter"); + ScopeLogger(); push_service_notification_h handle = nullptr; int ret = push_service_app_control_to_notification(app_control_, operation_, &handle); @@ -320,7 +320,7 @@ PlatformResult PushManager::getPushMessage(picojson::value* out) { } void PushManager::onPushState(push_service_state_e state, const char* err, void* user_data) { - LoggerD("Enter %d, err: %s", state, err); + ScopeLogger("state: %d; err: %s", (int)state, err); PushManager* impl = static_cast(user_data); if (nullptr == impl || !impl->m_listener) { LoggerW("Listener not set, ignoring"); @@ -336,7 +336,7 @@ void PushManager::onPushState(push_service_state_e state, const char* err, void* } void PushManager::onPushNotify(push_service_notification_h noti, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); PushManager* impl = static_cast(user_data); if (nullptr == impl || !impl->m_listener) { LoggerW("Listener not set, ignoring"); @@ -347,7 +347,7 @@ void PushManager::onPushNotify(push_service_notification_h noti, void* user_data void PushManager::onApplicationRegister(push_service_result_e result, const char* msg, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); PushManagerHolder* holder = static_cast(user_data); // automatically releases memory @@ -390,7 +390,7 @@ void PushManager::onApplicationRegister(push_service_result_e result, const char // TODO duplicated code due to different error handling in 2.4 API. remove on next release void PushManager::onApplicationRegister_2_4(push_service_result_e result, const char* msg, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); PushManagerHolder* holder = static_cast(user_data); // automatically releases memory @@ -434,7 +434,7 @@ void PushManager::onApplicationRegister_2_4(push_service_result_e result, const } void PushManager::onDeregister(push_service_result_e result, const char* msg, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); PushManagerHolder* holder = static_cast(user_data); // automatically releases memory PushManager* impl = dynamic_cast(holder->impl); @@ -460,7 +460,7 @@ void PushManager::onDeregister(push_service_result_e result, const char* msg, vo // TODO duplicated code due to different error handling in 2.4 API. remove on next release void PushManager::onDeregister_2_4(push_service_result_e result, const char* msg, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); PushManagerHolder* holder = static_cast(user_data); // automatically releases memory PushManager* impl = dynamic_cast(holder->impl); @@ -481,7 +481,7 @@ void PushManager::onDeregister_2_4(push_service_result_e result, const char* msg } gboolean PushManager::onFakeDeregister_2_4(gpointer user_data) { - LoggerD("Enter"); + ScopeLogger(); PushManagerHolder* holder = static_cast(user_data); // automatically releases memory std::unique_ptr holder_ptr(holder); diff --git a/src/push/push_manager_common.cc b/src/push/push_manager_common.cc index c8feace..406eb4c 100644 --- a/src/push/push_manager_common.cc +++ b/src/push/push_manager_common.cc @@ -33,7 +33,7 @@ using common::PlatformResult; using common::ErrorCode; std::string PushManagerCommon::StateToString(push_service_state_e state) { - LoggerD("Entered"); + ScopeLogger(); switch (state) { case PUSH_SERVICE_STATE_REGISTERED: @@ -44,7 +44,7 @@ std::string PushManagerCommon::StateToString(push_service_state_e state) { } std::string PushManagerCommon::GetEncodedBundle() { - LoggerD("Entered"); + ScopeLogger(); std::string result; std::size_t size = 512; @@ -61,7 +61,7 @@ std::string PushManagerCommon::GetEncodedBundle() { void PushManagerCommon::notificationToJson(push_service_notification_h noti, picojson::object* obj) { - LoggerD("Enter"); + ScopeLogger(); char* temp = nullptr; int ret = push_service_get_notification_data(noti, &temp); @@ -151,7 +151,7 @@ void PushManagerCommon::notificationToJson(push_service_notification_h noti, // 3.0 version errors mappings ErrorCode PushManagerCommon::ConvertPushError(int e) { - LoggerD("Enter"); + ScopeLogger(); ErrorCode error; switch (e) { @@ -173,7 +173,7 @@ ErrorCode PushManagerCommon::ConvertPushError(int e) { // Different error code mappings for 2.4 implementation ErrorCode PushManagerCommon::ConvertPushError_2_4(int e) { - LoggerD("Enter"); + ScopeLogger(); ErrorCode error; switch (e) { diff --git a/src/radio/radio_instance.cc b/src/radio/radio_instance.cc index d506196..1066c46 100644 --- a/src/radio/radio_instance.cc +++ b/src/radio/radio_instance.cc @@ -29,7 +29,7 @@ using namespace common; using namespace extension::radio; RadioInstance::RadioInstance() : manager_(*this) { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -54,59 +54,57 @@ RadioInstance::RadioInstance() : manager_(*this) { REGISTER_ASYNC("FMRadio_ScanStart", ScanStart); REGISTER_ASYNC("FMRadio_ScanStop", ScanStop); #undef REGISTER_ASYNC - - LoggerD("RadioInstance()"); } RadioInstance::~RadioInstance() { - LoggerD("Enter"); + ScopeLogger(); } void RadioInstance::MuteGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); ReportSuccess(picojson::value(manager_.IsMuted()), out); } void RadioInstance::MuteSetter(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.SetMute(args.get("mute").get()); ReportSuccess(out); } void RadioInstance::AntennaGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); ReportSuccess(picojson::value(manager_.HasAntenna()), out); } void RadioInstance::StateGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); ReportSuccess(picojson::value(manager_.GetState()), out); } void RadioInstance::FrequencyGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); ReportSuccess(picojson::value(manager_.GetFrequency()), out); } void RadioInstance::SignalStrengthGetter(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); ReportSuccess(picojson::value(manager_.GetSignalStrength()), out); } void RadioInstance::SeekUp(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.SeekUp(args.get("callbackId").get()); ReportSuccess(out); } void RadioInstance::SeekDown(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.SeekDown(args.get("callbackId").get()); ReportSuccess(out); } void RadioInstance::Start(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult result = manager_.Start(args.get("frequency").get()); @@ -118,7 +116,7 @@ void RadioInstance::Start(const picojson::value& args, picojson::object& out) { } void RadioInstance::Stop(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult result = manager_.Stop(); @@ -130,20 +128,20 @@ void RadioInstance::Stop(const picojson::value& args, picojson::object& out) { } void RadioInstance::ScanStart(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.ScanStart(args.get("callbackId").get()); ReportSuccess(out); } void RadioInstance::ScanStop(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.ScanStop(args.get("callbackId").get()); ReportSuccess(out); } void RadioInstance::SetFMRadioInterruptedListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult result = manager_.SetFMRadioInterruptedListener(); @@ -156,7 +154,7 @@ void RadioInstance::SetFMRadioInterruptedListener(const picojson::value& args, void RadioInstance::UnsetFMRadioInterruptedListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult result = manager_.UnsetFMRadioInterruptedListener(); @@ -168,7 +166,7 @@ void RadioInstance::UnsetFMRadioInterruptedListener(const picojson::value& args, } void RadioInstance::SetAntennaChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult result = manager_.SetAntennaChangeListener(); @@ -180,7 +178,7 @@ void RadioInstance::SetAntennaChangeListener(const picojson::value& args, picojs } void RadioInstance::UnsetAntennaChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult result = manager_.UnsetAntennaChangeListener(); diff --git a/src/radio/radio_manager.cc b/src/radio/radio_manager.cc index f348b37..e33cd4c 100644 --- a/src/radio/radio_manager.cc +++ b/src/radio/radio_manager.cc @@ -51,11 +51,12 @@ std::map radio_state = { static const double FREQ_LOWER = 87.5; static void AddCallbackID(double callbackId, picojson::object* obj) { + ScopeLogger(); obj->insert(std::make_pair("callbackId", picojson::value(callbackId))); } PlatformResult GetPlatformResult(const std::string& str, int err) { - LoggerD("Enter"); + ScopeLogger(); string message = str + " : " + to_string(err); @@ -75,6 +76,7 @@ PlatformResult GetPlatformResult(const std::string& str, int err) { } PlatformResult CheckError(const std::string& str, int err) { + ScopeLogger(); LoggerE("%s() error %d", str.c_str(), err); switch (err) { @@ -87,7 +89,7 @@ PlatformResult CheckError(const std::string& str, int err) { } string TranslateInterruptedCode(int code) { - LoggerD("Enter"); + ScopeLogger(); #define STRINGIFY(c) \ case c: \ return #c @@ -115,7 +117,7 @@ double ToMHz(int frequency) { } void RadioSeekCallback(int frequency, void* user_data) { - LoggerD("Enter, freq: %d", frequency); + ScopeLogger("freq: %d", frequency); RadioData* data = static_cast(user_data); @@ -131,7 +133,7 @@ void RadioSeekCallback(int frequency, void* user_data) { } void ScanStartCallback(int frequency, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); RadioScanData* data = static_cast(user_data); data->frequencies_.push_back(frequency); @@ -145,12 +147,13 @@ void ScanStartCallback(int frequency, void* user_data) { } void PostAsyncSuccess(FMRadioManager* manager, double callbackId, picojson::value* event) { + ScopeLogger(); manager->PostResultSuccess(callbackId, event); delete event; } void ScanCompleteCallback(void* user_data) { - LoggerD("Enter"); + ScopeLogger(); RadioScanData* data = static_cast(user_data); @@ -172,7 +175,7 @@ void ScanCompleteCallback(void* user_data) { } void ScanStopCallback(void* user_data) { - LoggerD("Enter"); + ScopeLogger(); RadioData* data = static_cast(user_data); common::TaskQueue::GetInstance().Async( @@ -183,7 +186,7 @@ void ScanStopCallback(void* user_data) { } void RadioInterruptedCallback(radio_interrupted_code_e code, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); picojson::value event{picojson::object()}; auto& obj = event.get(); @@ -203,7 +206,7 @@ void RadioInterruptedCallback(radio_interrupted_code_e code, void* user_data) { } void RadioAntennaCallback(runtime_info_key_e key, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); bool connected = false; const auto err = runtime_info_get_value_bool(key, &connected); @@ -225,7 +228,7 @@ void RadioAntennaCallback(runtime_info_key_e key, void* user_data) { } // namespace bool FMRadioManager::IsMuted() { - LoggerD("Enter"); + ScopeLogger(); bool muted = false; const auto err = radio_is_muted(radio_instance_, &muted); @@ -246,7 +249,7 @@ void FMRadioManager::SetScanData(RadioScanData* scan_data) { } void FMRadioManager::SetMute(bool mute) { - LoggerD("Enter"); + ScopeLogger(); const auto err = radio_set_mute(radio_instance_, mute); @@ -256,7 +259,7 @@ void FMRadioManager::SetMute(bool mute) { } bool FMRadioManager::HasAntenna() { - LoggerD("Enter"); + ScopeLogger(); bool connected = false; const auto err = runtime_info_get_value_bool(RUNTIME_INFO_KEY_AUDIO_JACK_CONNECTED, &connected); @@ -269,7 +272,7 @@ bool FMRadioManager::HasAntenna() { } const char* FMRadioManager::GetState() { - LoggerD("Enter"); + ScopeLogger(); radio_state_e state; @@ -291,12 +294,12 @@ const char* FMRadioManager::GetState() { } PlatformResult FMRadioManager::SetFrequency(double frequency) { - LoggerD("Enter"); + ScopeLogger(); return CheckError("radio_set_frequency", radio_set_frequency(radio_instance_, TokHz(frequency))); } double FMRadioManager::GetFrequency() { - LoggerD("Enter"); + ScopeLogger(); int frequency = 0; const auto err = radio_get_frequency(radio_instance_, &frequency); @@ -311,7 +314,7 @@ double FMRadioManager::GetFrequency() { } double FMRadioManager::GetSignalStrength() { - LoggerD("Enter"); + ScopeLogger(); int strength = 0; const auto err = radio_get_signal_strength(radio_instance_, &strength); @@ -326,7 +329,7 @@ double FMRadioManager::GetSignalStrength() { FMRadioManager::FMRadioManager(RadioInstance& instance) : instance_(instance), radio_instance_(nullptr), scan_data(nullptr) { - LoggerD("Enter"); + ScopeLogger(); const auto err = radio_create(&radio_instance_); @@ -337,7 +340,7 @@ FMRadioManager::FMRadioManager(RadioInstance& instance) } FMRadioManager::~FMRadioManager() { - LoggerD("Enter"); + ScopeLogger(); if (radio_instance_) { const auto err = radio_destroy(radio_instance_); @@ -350,7 +353,7 @@ FMRadioManager::~FMRadioManager() { } PlatformResult FMRadioManager::Start(double frequency) { - LoggerD("Enter, frequency: %f", frequency); + ScopeLogger("freq: %d", frequency); radio_state_e state; const auto err = radio_get_state(radio_instance_, &state); @@ -378,7 +381,7 @@ PlatformResult FMRadioManager::Start(double frequency) { } PlatformResult FMRadioManager::Stop() { - LoggerD("Enter"); + ScopeLogger(); radio_state_e state; const auto err = radio_get_state(radio_instance_, &state); @@ -396,7 +399,7 @@ PlatformResult FMRadioManager::Stop() { } void FMRadioManager::SeekUp(double callback_id) { - LoggerD("Enter"); + ScopeLogger(); RadioData* user_data = new RadioData(*this); user_data->callback_id_ = callback_id; @@ -411,7 +414,7 @@ void FMRadioManager::SeekUp(double callback_id) { } void FMRadioManager::SeekDown(double callback_id) { - LoggerD("Enter"); + ScopeLogger(); RadioData* user_data = new RadioData(*this); user_data->callback_id_ = callback_id; @@ -426,7 +429,7 @@ void FMRadioManager::SeekDown(double callback_id) { } void FMRadioManager::ScanStart(double callback_id) { - LoggerD("Enter"); + ScopeLogger(); radio_state_e state; auto err = radio_get_state(radio_instance_, &state); @@ -464,7 +467,7 @@ void FMRadioManager::ScanStart(double callback_id) { } void FMRadioManager::ScanStop(double callback_id) { - LoggerD("Enter"); + ScopeLogger(); RadioScanData* user_data = new RadioScanData(*this); user_data->callback_id_ = callback_id; @@ -490,21 +493,21 @@ void FMRadioManager::ScanStop(double callback_id) { } common::PlatformResult FMRadioManager::SetFMRadioInterruptedListener() { - LoggerD("Enter"); + ScopeLogger(); const auto err = radio_set_interrupted_cb(radio_instance_, RadioInterruptedCallback, this); return CheckError("radio_set_interrupted_cb", err); } common::PlatformResult FMRadioManager::UnsetFMRadioInterruptedListener() { - LoggerD("Enter"); + ScopeLogger(); const auto err = radio_unset_interrupted_cb(radio_instance_); return CheckError("radio_unset_interrupted_cb", err); } common::PlatformResult FMRadioManager::SetAntennaChangeListener() { - LoggerD("Enter"); + ScopeLogger(); const auto err = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_AUDIO_JACK_CONNECTED, RadioAntennaCallback, this); @@ -512,18 +515,19 @@ common::PlatformResult FMRadioManager::SetAntennaChangeListener() { } common::PlatformResult FMRadioManager::UnsetAntennaChangeListener() { - LoggerD("Enter"); + ScopeLogger(); const auto err = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_AUDIO_JACK_CONNECTED); return CheckError("runtime_info_unset_changed_cb", err); } void FMRadioManager::PostMessage(const std::string& msg) const { - LoggerD("Enter"); + ScopeLogger(); Instance::PostMessage(&instance_, msg.c_str()); } void FMRadioManager::PostResultSuccess(double callbackId, picojson::value* event) const { + ScopeLogger(); auto& obj = event->get(); tools::ReportSuccess(obj); @@ -533,12 +537,14 @@ void FMRadioManager::PostResultSuccess(double callbackId, picojson::value* event } void FMRadioManager::PostResultCallbackSuccess(double callbackId) const { + ScopeLogger(); picojson::value event{picojson::object()}; PostResultSuccess(callbackId, &event); } void FMRadioManager::PostResultFailure(double callbackId, const PlatformResult& result) const { + ScopeLogger(); picojson::value event{picojson::object()}; auto& obj = event.get(); diff --git a/src/secureelement/secureelement_instance.cc b/src/secureelement/secureelement_instance.cc index 4dbff5e..ac4139a 100644 --- a/src/secureelement/secureelement_instance.cc +++ b/src/secureelement/secureelement_instance.cc @@ -154,6 +154,7 @@ TizenResult SecureElementInstance::GetReaders(picojson::object const& args, CHECK_PRIVILEGE(kPrivilegeSecureElement); auto get_readers = [this](const common::AsyncToken& token) -> void { + ScopeLogger("Entered into asynchronous function, get_readers"); TizenResult result = TizenSuccess(); int* readers = nullptr; @@ -299,6 +300,7 @@ TizenResult SecureElementInstance::OpenSession(picojson::object const& args, int reader = static_cast(args.find(kHandle)->second.get()); auto open_session = [this, reader](const common::AsyncToken& token) -> void { + ScopeLogger("Entered into asynchronous function, open_session"); TizenResult result = TizenSuccess(); int session = 0; @@ -364,6 +366,7 @@ TizenResult SecureElementInstance::OpenBasicChannel(picojson::object const& args const picojson::array v_aid = args.find(kAid)->second.get(); auto open_basic_channel = [this, session, v_aid](const common::AsyncToken& token) -> void { + ScopeLogger("Entered into asynchronous function, open_basic_channel"); TizenResult result = TizenSuccess(); int channel = 0; unsigned char P2 = 0; @@ -408,6 +411,7 @@ TizenResult SecureElementInstance::OpenLogicalChannel(picojson::object const& ar const picojson::array v_aid = args.find(kAid)->second.get(); auto open_basic_logical = [this, session, v_aid](const common::AsyncToken& token) -> void { + ScopeLogger("Entered into asynchronous function, open_basic_logical"); TizenResult result = TizenSuccess(); int channel = 0; unsigned char P2 = 0; @@ -540,6 +544,7 @@ TizenResult SecureElementInstance::Transmit(picojson::object const& args, const auto& v_cmd = args.find(kCommand)->second.get(); auto transmit = [this, channel, v_cmd](const common::AsyncToken& token) -> void { + ScopeLogger("Entered into asynchronous function, transmit"); TizenResult result = TizenSuccess(); size_t v_cmd_size = v_cmd.size(); diff --git a/src/sensor/sensor_instance.cc b/src/sensor/sensor_instance.cc index 1165487..b137ef0 100644 --- a/src/sensor/sensor_instance.cc +++ b/src/sensor/sensor_instance.cc @@ -26,7 +26,7 @@ namespace sensor { using namespace common; SensorInstance::SensorInstance() : service_(*this) { - LoggerD("Entered"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -44,42 +44,42 @@ SensorInstance::SensorInstance() : service_(*this) { } SensorInstance::~SensorInstance() { - LoggerD("Entered"); + ScopeLogger(); } void SensorInstance::GetAvailableSensors(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); service_.GetAvailableSensors(out); } void SensorInstance::SensorStop(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); service_.SensorStop(args, out); } void SensorInstance::SensorSetChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); service_.SensorSetChangeListener(args, out); } void SensorInstance::SensorUnsetChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); service_.SensorUnsetChangeListener(args, out); } void SensorInstance::SensorStart(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); service_.SensorStart(args, out); } void SensorInstance::SensorGetData(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); service_.GetSensorData(args, out); } void SensorInstance::GetSensorHardwareInfo(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); service_.GetSensorHardwareInfo(args, out); } diff --git a/src/sensor/sensor_service.cc b/src/sensor/sensor_service.cc index 2cd3ed6..b6b87fe 100644 --- a/src/sensor/sensor_service.cc +++ b/src/sensor/sensor_service.cc @@ -46,7 +46,7 @@ static std::map type_to_string_map; static std::map string_to_type_map; static std::string GetAccuracyString(int accuracy) { - LoggerD("Entered"); + ScopeLogger(); switch (static_cast(accuracy)) { case SENSOR_DATA_ACCURACY_BAD: return "ACCURACY_BAD"; @@ -69,7 +69,7 @@ static const std::string kSensorChangedListener = "SensorChangedListener"; void ReportSensorData(sensor_type_e sensor_type, sensor_event_s* sensor_event, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); switch (sensor_type) { case SENSOR_LIGHT: { @@ -138,7 +138,7 @@ void ReportSensorData(sensor_type_e sensor_type, sensor_event_s* sensor_event, } std::string GetSensorErrorMessage(const int error_code) { - LoggerD("Entered"); + ScopeLogger(); switch (error_code) { case SENSOR_ERROR_IO_ERROR: @@ -161,7 +161,7 @@ std::string GetSensorErrorMessage(const int error_code) { } PlatformResult GetSensorPlatformResult(const int error_code, const std::string& hint) { - LoggerD("Entered"); + ScopeLogger(); std::string message = hint + " : " + GetSensorErrorMessage(error_code); @@ -176,6 +176,7 @@ PlatformResult GetSensorPlatformResult(const int error_code, const std::string& } bool DefaultEventComparator(sensor_event_s* l, sensor_event_s* r, const unsigned int value_count) { + ScopeLogger(); for (unsigned int i = 0; i < value_count; ++i) { if (l->values[i] != r->values[i]) { return false; @@ -252,14 +253,14 @@ SensorData::SensorData(SensorInstance& instance, sensor_type_e type_enum, const instance_(instance), is_change_listener_set_(false), is_starting_(false) { + ScopeLogger(); type_to_string_map.insert(std::make_pair(type_enum, name)); string_to_type_map.insert(std::make_pair(name, type_enum)); - - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + LoggerD("type_to_string_map is: %s", type_to_string_map[type()].c_str()); } SensorData::~SensorData() { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); if (listener_) { sensor_destroy_listener(listener_); @@ -267,7 +268,7 @@ SensorData::~SensorData() { } void SensorData::SensorCallback(sensor_h sensor, sensor_event_s* event, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); SensorData* that = static_cast(user_data); @@ -276,14 +277,15 @@ void SensorData::SensorCallback(sensor_h sensor, sensor_event_s* event, void* us return; } - LoggerD("Entered: %s", type_to_string_map[that->type()].c_str()); + LoggerD("sensor type: %s", type_to_string_map[that->type()].c_str()); { std::lock_guard lock(that->change_listener_mutex_); if (!that->delayed_success_callbacks_.empty()) { for_each(that->delayed_success_callbacks_.begin(), that->delayed_success_callbacks_.end(), [](std::function& callback) { - LoggerD("Calling delayed start succcess callback"); + ScopeLogger( + "Entered into asynchronous function, calling delayed start succcess callback"); callback(); }); that->delayed_success_callbacks_.erase(that->delayed_success_callbacks_.begin(), @@ -311,7 +313,7 @@ void SensorData::SensorCallback(sensor_h sensor, sensor_event_s* event, void* us } PlatformResult SensorData::CheckInitialization() { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); std::lock_guard lock(initialization_mutex_); if (!handle_) { @@ -334,7 +336,7 @@ PlatformResult SensorData::CheckInitialization() { } PlatformResult SensorData::IsSupported(bool* supported) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); if (!is_supported_) { bool is_supported = false; @@ -351,7 +353,7 @@ PlatformResult SensorData::IsSupported(bool* supported) { } PlatformResult SensorData::IsSupportedImpl(bool* supported) const { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); bool is_supported = false; int ret = sensor_is_supported(type_enum_, &is_supported); @@ -366,7 +368,7 @@ PlatformResult SensorData::IsSupportedImpl(bool* supported) const { } bool SensorData::is_supported() { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); if (!is_supported_) { bool is_supported = false; @@ -382,7 +384,7 @@ bool SensorData::is_supported() { } bool SensorData::UpdateEvent(sensor_event_s* event) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); if (comparator_(&previous_event_, event, sensor_value_count_)) { // previous and current events are the same -> no update @@ -394,7 +396,7 @@ bool SensorData::UpdateEvent(sensor_event_s* event) { } PlatformResult SensorData::AddDelayedStartSuccessCb(const std::function& successCb) { - LoggerD("Entered"); + ScopeLogger("Entered"); delayed_success_callbacks_.push_back(successCb); if (!is_change_listener_set_ && !is_starting_) { @@ -418,7 +420,7 @@ PlatformResult SensorData::AddDelayedStartSuccessCb(const std::function& PlatformResult SensorData::Start( const std::shared_ptr& result, const std::function&)>& report_result) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); auto res = CheckInitialization(); if (!res) { @@ -427,7 +429,7 @@ PlatformResult SensorData::Start( } auto delayed_success_callback = [this, result, report_result]() { - LoggerD("Delayed success callback"); + ScopeLogger("Entered into asynchronous function, delayed succcess callback"); ReportSuccess(result->get()); report_result(result); }; @@ -458,7 +460,7 @@ PlatformResult SensorData::Start( } PlatformResult SensorData::Stop() { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); auto res = CheckInitialization(); @@ -487,7 +489,7 @@ PlatformResult SensorData::Stop() { } PlatformResult SensorData::SetChangeListener(unsigned int interval, unsigned int batch_latency) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); auto res = CheckInitialization(); @@ -518,7 +520,7 @@ PlatformResult SensorData::SetChangeListener(unsigned int interval, unsigned int } PlatformResult SensorData::UnsetChangeListener() { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); auto res = CheckInitialization(); @@ -542,7 +544,7 @@ PlatformResult SensorData::UnsetChangeListener() { } PlatformResult SensorData::GetSensorData(picojson::object* data) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); auto res = CheckInitialization(); @@ -564,7 +566,7 @@ PlatformResult SensorData::GetSensorData(picojson::object* data) { } PlatformResult SensorData::GetHardwareInfo(picojson::object* data) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); auto res = CheckInitialization(); @@ -588,6 +590,7 @@ PlatformResult SensorData::GetHardwareInfo(picojson::object* data) { }; auto native_result = [](int ret) -> PlatformResult { + ScopeLogger("Entered into asynchronous function, native_result"); switch (ret) { case SENSOR_ERROR_IO_ERROR: return PlatformResult(ErrorCode::IO_ERR); @@ -683,7 +686,7 @@ class HrmSensorData : public SensorData { HrmSensorData::HrmSensorData(SensorInstance& instance) : SensorData(instance, SENSOR_CUSTOM, "HRM_RAW", 1) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); // For amount of retrieved values from sensors please refer to native guides. AddSensor(new SensorData(instance, SENSOR_HRM_LED_IR, "LED_IR", 1)); AddSensor(new SensorData(instance, SENSOR_HRM_LED_RED, "LED_RED", 1)); @@ -691,16 +694,16 @@ HrmSensorData::HrmSensorData(SensorInstance& instance) } HrmSensorData::~HrmSensorData() { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); } void HrmSensorData::AddSensor(SensorData* sensor) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); hrm_sensors_.insert(std::make_pair(sensor->type(), std::shared_ptr(sensor))); } PlatformResult HrmSensorData::CallMember(PlatformResult (SensorData::*member)()) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); bool is_any_supported = false; for (const auto& sensor : hrm_sensors_) { if (sensor.second->is_supported()) { @@ -724,7 +727,7 @@ PlatformResult HrmSensorData::CallMember( const std::function&)>&), const std::shared_ptr& result, const std::function&)>& work) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); bool is_any_supported = false; for (const auto& sensor : hrm_sensors_) { if (sensor.second->is_supported()) { @@ -743,7 +746,7 @@ PlatformResult HrmSensorData::CallMember( } PlatformResult HrmSensorData::IsSupportedImpl(bool* supported) const { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); bool result = false; bool hrm_supported = false; @@ -770,17 +773,17 @@ PlatformResult HrmSensorData::IsSupportedImpl(bool* supported) const { PlatformResult HrmSensorData::Start( const std::shared_ptr& result, const std::function&)>& work) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); return CallMember(&SensorData::Start, result, work); } PlatformResult HrmSensorData::Stop() { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); return CallMember(&SensorData::Stop); } PlatformResult HrmSensorData::SetChangeListener(unsigned int interval, unsigned int batch_latency) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); for (const auto& sensor : hrm_sensors_) { if (sensor.second->is_supported()) { auto res = sensor.second->SetChangeListener(interval, batch_latency); @@ -793,12 +796,12 @@ PlatformResult HrmSensorData::SetChangeListener(unsigned int interval, unsigned } PlatformResult HrmSensorData::UnsetChangeListener() { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); return CallMember(&SensorData::UnsetChangeListener); } PlatformResult HrmSensorData::GetSensorData(picojson::object* data) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); for (const auto& sensor : hrm_sensors_) { if (sensor.second->is_supported()) { // HRMRawSensor.getHRMRawSensorData() can return only one value, @@ -820,7 +823,7 @@ PlatformResult HrmSensorData::GetSensorData(picojson::object* data) { } PlatformResult HrmSensorData::GetHardwareInfo(picojson::object* data) { - LoggerD("Entered: %s", type_to_string_map[type()].c_str()); + ScopeLogger(type_to_string_map[type()]); for (const auto& sensor : hrm_sensors_) { if (sensor.second->is_supported()) { return sensor.second->GetHardwareInfo(data); @@ -831,7 +834,7 @@ PlatformResult HrmSensorData::GetHardwareInfo(picojson::object* data) { } SensorService::SensorService(SensorInstance& instance) : instance_(instance) { - LoggerD("Entered"); + ScopeLogger(); // For amount of retrieved values from sensors please refer to native guides. AddSensor(new SensorData(instance, SENSOR_LIGHT, "LIGHT", 1)); @@ -848,11 +851,11 @@ SensorService::SensorService(SensorInstance& instance) : instance_(instance) { } SensorService::~SensorService() { - LoggerD("Entered"); + ScopeLogger(); } void SensorService::GetAvailableSensors(picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); bool is_supported = false; @@ -876,7 +879,7 @@ void SensorService::GetAvailableSensors(picojson::object& out) { } void SensorService::SensorStart(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, "callbackId", out) int callback_id = static_cast(args.get("callbackId").get()); const std::string type_str = @@ -886,7 +889,7 @@ void SensorService::SensorStart(const picojson::value& args, picojson::object& o sensor_type_e type_enum = string_to_type_map[type_str]; auto start_result = [this, callback_id](const std::shared_ptr& result) { - LoggerD("Entered"); + ScopeLogger("Entered into asynchronous function, start_result"); result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; Instance::PostMessage(&instance_, result->serialize().c_str()); @@ -894,7 +897,8 @@ void SensorService::SensorStart(const picojson::value& args, picojson::object& o auto start = [this, type_enum, type_str, start_result](const std::shared_ptr& result) { - LoggerD("Entered"); + + ScopeLogger("Entered into asynchronous function, start"); auto sensor_data = GetSensor(type_enum); if (!sensor_data) { LogAndReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Sensor data is null"), @@ -917,7 +921,7 @@ void SensorService::SensorStart(const picojson::value& args, picojson::object& o } void SensorService::SensorStop(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const std::string type_str = args.contains(kSensorTypeTag) ? args.get(kSensorTypeTag).get() : ""; LoggerD("input type: %s", type_str.c_str()); @@ -939,7 +943,7 @@ void SensorService::SensorStop(const picojson::value& args, picojson::object& ou } void SensorService::SensorSetChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const std::string type_str = args.contains(kSensorTypeTag) ? args.get(kSensorTypeTag).get() : ""; const auto interval = args.contains(kInterval) ? args.get(kInterval).get() : 100.0; @@ -968,7 +972,7 @@ void SensorService::SensorSetChangeListener(const picojson::value& args, picojso } void SensorService::SensorUnsetChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const std::string type_str = args.contains(kSensorTypeTag) ? args.get(kSensorTypeTag).get() : ""; LoggerD("input type: %s", type_str.c_str()); @@ -991,7 +995,7 @@ void SensorService::SensorUnsetChangeListener(const picojson::value& args, picoj } std::shared_ptr SensorService::GetSensor(sensor_type_e type_enum) { - LoggerD("Entered"); + ScopeLogger(); auto sensor = sensors_.find(type_enum); if (sensors_.end() == sensor) { @@ -1002,12 +1006,12 @@ std::shared_ptr SensorService::GetSensor(sensor_type_e type_enum) { } void SensorService::AddSensor(SensorData* sensor) { - LoggerD("Entered"); + ScopeLogger(); sensors_.insert(std::make_pair(sensor->type(), std::shared_ptr(sensor))); } void SensorService::GetSensorData(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, "callbackId", out); CHECK_EXIST(args, "type", out); @@ -1016,6 +1020,7 @@ void SensorService::GetSensorData(const picojson::value& args, picojson::object& sensor_type_e sensor_type = string_to_type_map[args.get("type").get()]; auto get_data = [this, sensor_type](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function, get_data"); picojson::object& object = result->get(); auto sensor_data = this->GetSensor(sensor_type); @@ -1034,6 +1039,7 @@ void SensorService::GetSensorData(const picojson::value& args, picojson::object& }; auto get_data_result = [this, callback_id](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function, get_data_result"); result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; @@ -1048,7 +1054,7 @@ void SensorService::GetSensorData(const picojson::value& args, picojson::object& } void SensorService::GetSensorHardwareInfo(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); CHECK_EXIST(args, "callbackId", out); CHECK_EXIST(args, "type", out); @@ -1057,6 +1063,7 @@ void SensorService::GetSensorHardwareInfo(const picojson::value& args, picojson: sensor_type_e sensor_type = string_to_type_map[args.get("type").get()]; auto get_info = [this, sensor_type](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function, get_info"); picojson::object& object = result->get(); auto sensor_data = this->GetSensor(sensor_type); @@ -1079,6 +1086,7 @@ void SensorService::GetSensorHardwareInfo(const picojson::value& args, picojson: }; auto get_info_result = [this, callback_id](const std::shared_ptr& result) { + ScopeLogger("Entered into asynchronous function, get_info_result"); result->get()["callbackId"] = picojson::value{static_cast(callback_id)}; Instance::PostMessage(&instance_, result->serialize().c_str()); diff --git a/src/sound/sound_instance.cc b/src/sound/sound_instance.cc index 3b99ef3..89e0b86 100644 --- a/src/sound/sound_instance.cc +++ b/src/sound/sound_instance.cc @@ -37,7 +37,7 @@ using namespace common; using namespace extension::sound; SoundInstance::SoundInstance() : manager_(*this) { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -60,7 +60,7 @@ SoundInstance::SoundInstance() : manager_(*this) { } SoundInstance::~SoundInstance() { - LoggerD("Enter"); + ScopeLogger(); } #define CHECK_EXIST(args, name, out) \ @@ -70,7 +70,7 @@ SoundInstance::~SoundInstance() { } void SoundInstance::SoundManagerGetSoundMode(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); std::string sound_mode_type; PlatformResult status = manager_.GetSoundMode(&sound_mode_type); @@ -82,7 +82,7 @@ void SoundInstance::SoundManagerGetSoundMode(const picojson::value& args, picojs } void SoundInstance::SoundManagerSetVolume(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeSound, &out); PlatformResult status = manager_.SetVolume(args.get()); @@ -94,7 +94,7 @@ void SoundInstance::SoundManagerSetVolume(const picojson::value& args, picojson: } void SoundInstance::SoundManagerGetVolume(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); double volume; PlatformResult status = manager_.GetVolume(args.get(), &volume); @@ -107,7 +107,7 @@ void SoundInstance::SoundManagerGetVolume(const picojson::value& args, picojson: void SoundInstance::SoundManagerSetSoundModeChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = manager_.SetSoundModeChangeListener(this); if (status.IsSuccess()) { @@ -121,7 +121,7 @@ void SoundInstance::SoundManagerUnsetSoundModeChangeListener(const picojson::val picojson::object& out) { PlatformResult status = manager_.UnsetSoundModeChangeListener(); - LoggerD("Enter"); + ScopeLogger(); if (status.IsSuccess()) { ReportSuccess(out); @@ -131,7 +131,7 @@ void SoundInstance::SoundManagerUnsetSoundModeChangeListener(const picojson::val } void SoundInstance::OnSoundModeChange(const std::string& newmode) { - LoggerD("Enter"); + ScopeLogger(); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); picojson::value result = picojson::value(newmode); @@ -143,7 +143,7 @@ void SoundInstance::OnSoundModeChange(const std::string& newmode) { void SoundInstance::SoundManagerSetVolumeChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = manager_.SetVolumeChangeListener(); if (status.IsSuccess()) { @@ -155,7 +155,7 @@ void SoundInstance::SoundManagerSetVolumeChangeListener(const picojson::value& a void SoundInstance::SoundManagerUnsetVolumeChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); PlatformResult status = manager_.UnsetVolumeChangeListener(); if (status.IsSuccess()) { @@ -167,19 +167,19 @@ void SoundInstance::SoundManagerUnsetVolumeChangeListener(const picojson::value& void SoundInstance::SoundManagerGetConnectedDeviceList(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); manager_.GetDeviceList(SOUND_DEVICE_ALL_MASK, out); } void SoundInstance::SoundManagerGetActivatedDeviceList(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); manager_.GetDeviceList(SOUND_DEVICE_STATE_ACTIVATED_MASK, out); } void SoundInstance::SoundManagerAddDeviceStateChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult result = manager_.AddDeviceStateChangeListener(); if (result.IsSuccess()) { @@ -191,7 +191,7 @@ void SoundInstance::SoundManagerAddDeviceStateChangeListener(const picojson::val void SoundInstance::SoundManagerRemoveDeviceStateChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult result = manager_.RemoveDeviceStateChangeListener(); if (result.IsSuccess()) { diff --git a/src/sound/sound_manager.cc b/src/sound/sound_manager.cc index 794e9c4..3174436 100644 --- a/src/sound/sound_manager.cc +++ b/src/sound/sound_manager.cc @@ -50,7 +50,7 @@ const std::map SoundManager::platform_enum_map_ = { {"VOICE", SOUND_TYPE_VOICE}, {"RINGTONE", SOUND_TYPE_RINGTONE}}; PlatformResult SoundManager::StrToPlatformEnum(const std::string& key, sound_type_e* sound_type) { - LoggerD("Enter"); + ScopeLogger(); if (platform_enum_map_.find(key) == platform_enum_map_.end()) { std::string message = "Platform enum value not found for key " + key; return LogAndCreateResult(ErrorCode::INVALID_VALUES_ERR, message); @@ -62,7 +62,7 @@ PlatformResult SoundManager::StrToPlatformEnum(const std::string& key, sound_typ } PlatformResult SoundManager::PlatformEnumToStr(const sound_type_e value, std::string* sound_type) { - LoggerD("Enter"); + ScopeLogger(); for (auto& item : platform_enum_map_) { if (item.second == value) { *sound_type = item.first; @@ -77,7 +77,7 @@ PlatformResult SoundManager::PlatformEnumToStr(const sound_type_e value, std::st } std::string SoundManager::SoundDeviceTypeToString(sound_device_type_e type) { - LoggerD("Enter"); + ScopeLogger(); switch (type) { case SOUND_DEVICE_BUILTIN_SPEAKER: return "SPEAKER"; @@ -102,7 +102,7 @@ std::string SoundManager::SoundDeviceTypeToString(sound_device_type_e type) { } std::string SoundManager::SoundIOTypeToString(sound_device_io_direction_e type) { - LoggerD("Enter"); + ScopeLogger(); switch (type) { case SOUND_DEVICE_IO_DIRECTION_IN: return "IN"; @@ -125,11 +125,12 @@ SoundManager::SoundManager(SoundInstance& instance) sound_device_state_listener_id_(0), instance_(instance), soundModeListener(nullptr) { + ScopeLogger(); FillMaxVolumeMap(); } SoundManager::~SoundManager() { - LoggerD("Enter"); + ScopeLogger(); UnsetSoundModeChangeListener(); @@ -155,7 +156,7 @@ SoundManager::~SoundManager() { } void SoundManager::FillMaxVolumeMap() { - LoggerD("Enter"); + ScopeLogger(); int max = 100; int ret; @@ -174,7 +175,7 @@ void SoundManager::FillMaxVolumeMap() { } PlatformResult SoundManager::GetMaxVolume(sound_type_e type, int* max_volume) { - LoggerD("Enter"); + ScopeLogger(); auto it = max_volume_map_.find(type); if (it == max_volume_map_.end()) { std::string sound_type; @@ -191,12 +192,12 @@ PlatformResult SoundManager::GetMaxVolume(sound_type_e type, int* max_volume) { } double SoundManager::ConvertToSystemVolume(int max_volume, int volume) { - LoggerD("Enter"); + ScopeLogger(); return round(static_cast(volume) * 100 / max_volume) / 100; } void SoundManager::VolumeChangeCallback(sound_type_e type, unsigned int value) { - LoggerD("VolumeChangeCallback: type: %d, value: %d", type, value); + ScopeLogger("VolumeChangeCallback: type: %d, value: %d", type, value); // Prepare response picojson::value response = picojson::value(picojson::object()); @@ -221,7 +222,7 @@ void SoundManager::VolumeChangeCallback(sound_type_e type, unsigned int value) { } PlatformResult SoundManager::GetSoundMode(std::string* sound_mode_type) { - LoggerD("Enter"); + ScopeLogger(); int isEnableSound = 0; int isEnableVibrate = 0; @@ -254,7 +255,7 @@ PlatformResult SoundManager::GetSoundMode(std::string* sound_mode_type) { } PlatformResult SoundManager::SetVolume(const picojson::object& args) { - LoggerD("Enter"); + ScopeLogger(); const std::string& type = FromJson(args, "type"); double volume = FromJson(args, "volume"); @@ -290,7 +291,7 @@ PlatformResult SoundManager::SetVolume(const picojson::object& args) { } PlatformResult SoundManager::GetVolume(const picojson::object& args, double* volume) { - LoggerD("Enter"); + ScopeLogger(); const std::string& type = FromJson(args, "type"); int value = 0; @@ -315,7 +316,7 @@ PlatformResult SoundManager::GetVolume(const picojson::object& args, double* vol } void SoundManager::soundModeChangedCb(keynode_t*, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); if (nullptr == user_data) { LoggerE("Invalid callback data!"); @@ -338,7 +339,7 @@ void SoundManager::soundModeChangedCb(keynode_t*, void* user_data) { PlatformResult SoundManager::SetSoundModeChangeListener( SoundManagerSoundModeChangedListener* listener) { - LoggerD("Enter"); + ScopeLogger(); soundModeListener = listener; if (soundModeChangeListening) return PlatformResult(ErrorCode::NO_ERROR); @@ -359,7 +360,7 @@ PlatformResult SoundManager::SetSoundModeChangeListener( } PlatformResult SoundManager::UnsetSoundModeChangeListener() { - LoggerD("Enter"); + ScopeLogger(); soundModeListener = nullptr; if (!soundModeChangeListening) { return PlatformResult(ErrorCode::NO_ERROR); @@ -382,10 +383,12 @@ PlatformResult SoundManager::UnsetSoundModeChangeListener() { } PlatformResult SoundManager::SetVolumeChangeListener() { - LoggerD("Enter"); + ScopeLogger(); if (!is_volume_change_listener_) { int ret = sound_manager_add_volume_changed_cb( [](sound_type_e type, unsigned int value, void* ud) { + ScopeLogger( + "Entered into asynchronous function, sound_manager_add_volume_changed_cb's argument"); return static_cast(ud)->VolumeChangeCallback(type, value); }, static_cast(this), &volume_change_listener_id_); @@ -403,7 +406,7 @@ PlatformResult SoundManager::SetVolumeChangeListener() { } PlatformResult SoundManager::UnsetVolumeChangeListener() { - LoggerD("Enter"); + ScopeLogger(); if (!is_volume_change_listener_) { return PlatformResult(ErrorCode::NO_ERROR); } @@ -421,7 +424,7 @@ PlatformResult SoundManager::UnsetVolumeChangeListener() { } void SoundManager::GetDeviceList(sound_device_mask_e mask, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); sound_device_list_h device_list = nullptr; sound_device_h device = nullptr; @@ -460,7 +463,7 @@ void SoundManager::GetDeviceList(sound_device_mask_e mask, picojson::object& out PlatformResult SoundManager::GetDeviceInfo(sound_device_h device, bool is_connected, bool check_connection, picojson::object* obj) { - LoggerD("Entered"); + ScopeLogger(); // get id int id = 0; @@ -524,7 +527,7 @@ PlatformResult SoundManager::GetDeviceInfo(sound_device_h device, bool is_connec PlatformResult SoundManager::IsDeviceConnected(sound_device_type_e type, sound_device_io_direction_e direction, picojson::object* obj) { - LoggerD("Entered"); + ScopeLogger(); sound_device_mask_e mask = SOUND_DEVICE_ALL_MASK; switch (direction) { @@ -578,7 +581,7 @@ PlatformResult SoundManager::IsDeviceConnected(sound_device_type_e type, } void SoundManager::DeviceChangeCB(sound_device_h device, bool is_connected, bool check_connection) { - LoggerD("Entered"); + ScopeLogger(); picojson::value response = picojson::value(picojson::object()); picojson::object& response_obj = response.get(); @@ -590,6 +593,7 @@ void SoundManager::DeviceChangeCB(sound_device_h device, bool is_connected, bool std::make_pair("listenerId", picojson::value("SoundDeviceStateChangeCallback"))); auto call_response = [this, response]() -> void { + ScopeLogger("Entered into asynchronous function, call_response"); Instance::PostMessage(&instance_, response.serialize().c_str()); }; @@ -598,21 +602,21 @@ void SoundManager::DeviceChangeCB(sound_device_h device, bool is_connected, bool } void DeviceConnectionChangedCB(sound_device_h device, bool is_connected, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); SoundManager* h = static_cast(user_data); h->DeviceChangeCB(device, is_connected, false); } void DeviceStateChangedCB(sound_device_h device, sound_device_state_e unused, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); SoundManager* h = static_cast(user_data); h->DeviceChangeCB(device, false, true); } PlatformResult SoundManager::AddDeviceStateChangeListener() { - LoggerD("Entered"); + ScopeLogger(); int ret = SOUND_MANAGER_ERROR_NONE; sound_device_mask_e mask = SOUND_DEVICE_ALL_MASK; @@ -643,7 +647,7 @@ PlatformResult SoundManager::AddDeviceStateChangeListener() { } PlatformResult SoundManager::RemoveDeviceStateChangeListener() { - LoggerD("Entered"); + ScopeLogger(); if (is_sound_device_change_listener_) { int ret = diff --git a/src/systeminfo/systeminfo-utils.cpp b/src/systeminfo/systeminfo-utils.cpp index d273da3..8882280 100644 --- a/src/systeminfo/systeminfo-utils.cpp +++ b/src/systeminfo/systeminfo-utils.cpp @@ -37,6 +37,7 @@ using common::PlatformResult; using common::ErrorCode; PlatformResult SysteminfoUtils::GetVconfInt(const char *key, int *value) { + ScopeLogger(); if (0 == vconf_get_int(key, value)) { LoggerD("value[%s]: %d", key, *value); return PlatformResult(ErrorCode::NO_ERROR); @@ -47,6 +48,7 @@ PlatformResult SysteminfoUtils::GetVconfInt(const char *key, int *value) { PlatformResult SysteminfoUtils::GetRuntimeInfoString(system_settings_key_e key, std::string *platform_string) { + ScopeLogger(); char *platform_c_string; int err = system_settings_get_value_string(key, &platform_c_string); if (SYSTEM_SETTINGS_ERROR_NONE == err) { @@ -62,6 +64,7 @@ PlatformResult SysteminfoUtils::GetRuntimeInfoString(system_settings_key_e key, } PlatformResult SysteminfoUtils::CheckTelephonySupport() { + ScopeLogger(); bool supported = false; PlatformResult ret = SystemInfoDeviceCapability::GetValueBool("tizen.org/feature/network.telephony", &supported); @@ -76,6 +79,7 @@ PlatformResult SysteminfoUtils::CheckTelephonySupport() { } PlatformResult SysteminfoUtils::CheckCameraFlashSupport() { + ScopeLogger(); bool supported = false; PlatformResult ret = SystemInfoDeviceCapability::GetValueBool("tizen.org/feature/camera.back.flash", &supported); @@ -90,7 +94,7 @@ PlatformResult SysteminfoUtils::CheckCameraFlashSupport() { } PlatformResult SysteminfoUtils::CheckIfEthernetNetworkSupported() { - LoggerD("Entered"); + ScopeLogger(); connection_h connection_handle = nullptr; connection_ethernet_state_e connection_state = CONNECTION_ETHERNET_STATE_DEACTIVATED; @@ -115,7 +119,7 @@ PlatformResult SysteminfoUtils::CheckIfEthernetNetworkSupported() { } PlatformResult SysteminfoUtils::GetTotalMemory(long long *result) { - LoggerD("Entered"); + ScopeLogger(); unsigned int value = 0; @@ -133,7 +137,7 @@ PlatformResult SysteminfoUtils::GetTotalMemory(long long *result) { } PlatformResult SysteminfoUtils::GetAvailableMemory(long long *result) { - LoggerD("Entered"); + ScopeLogger(); unsigned int value = 0; @@ -151,6 +155,7 @@ PlatformResult SysteminfoUtils::GetAvailableMemory(long long *result) { PlatformResult SysteminfoUtils::RegisterVconfCallback(const char *in_key, vconf_callback_fn cb, void *event_ptr) { + ScopeLogger(); if (0 != vconf_notify_key_changed(in_key, cb, event_ptr)) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to register vconf callback", ("Failed to register vconf callback: %s", in_key)); @@ -159,6 +164,7 @@ PlatformResult SysteminfoUtils::RegisterVconfCallback(const char *in_key, vconf_ } PlatformResult SysteminfoUtils::UnregisterVconfCallback(const char *in_key, vconf_callback_fn cb) { + ScopeLogger(); if (0 != vconf_ignore_key_changed(in_key, cb)) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to unregister vconf callback", ("Failed to unregister vconf callback: %s", in_key)); @@ -169,6 +175,7 @@ PlatformResult SysteminfoUtils::UnregisterVconfCallback(const char *in_key, vcon PlatformResult SysteminfoUtils::RegisterTapiChangeCallback(TapiHandle *handle, const char *noti_id, tapi_notification_cb callback, void *user_data) { + ScopeLogger(); int ntv_ret = tel_register_noti_event(handle, noti_id, callback, user_data); if (TAPI_API_SUCCESS != ntv_ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to register tapi callback", @@ -180,6 +187,7 @@ PlatformResult SysteminfoUtils::RegisterTapiChangeCallback(TapiHandle *handle, c PlatformResult SysteminfoUtils::UnregisterTapiChangeCallback(TapiHandle *handle, const char *noti_id) { + ScopeLogger(); int ntv_ret = tel_deregister_noti_event(handle, noti_id); if (TAPI_API_SUCCESS != ntv_ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to unregister tapi callback", diff --git a/src/systeminfo/systeminfo_device_capability.cc b/src/systeminfo/systeminfo_device_capability.cc index ad3a61a..5f537ee 100644 --- a/src/systeminfo/systeminfo_device_capability.cc +++ b/src/systeminfo/systeminfo_device_capability.cc @@ -86,6 +86,7 @@ const char* kTizenFeaturePlatformVersionName = "http://tizen.org/feature/platfor } // namespace PlatformResult SystemInfoDeviceCapability::GetValueBool(const char* key, bool* value) { + ScopeLogger(); bool platform_result = false; int ret = system_info_get_platform_bool(key, &platform_result); if (SYSTEM_INFO_ERROR_NONE != ret) { @@ -105,6 +106,7 @@ PlatformResult SystemInfoDeviceCapability::GetValueBool(const char* key, bool* v } PlatformResult SystemInfoDeviceCapability::GetValueInt(const char* key, int* value) { + ScopeLogger(); int platform_result = 0; int ret = system_info_get_platform_int(key, &platform_result); if (SYSTEM_INFO_ERROR_NONE != ret) { @@ -124,6 +126,7 @@ PlatformResult SystemInfoDeviceCapability::GetValueInt(const char* key, int* val } PlatformResult SystemInfoDeviceCapability::GetValueString(const char* key, std::string* str_value) { + ScopeLogger(); char* value = nullptr; int ret = system_info_get_platform_string(key, &value); @@ -150,7 +153,7 @@ PlatformResult SystemInfoDeviceCapability::GetValueString(const char* key, std:: static PlatformResult CheckStringCapability(const std::string& key, std::string* value, bool* fetched) { - LoggerD("Entered CheckStringCapability"); + ScopeLogger(); *fetched = false; if (kTizenFeatureOpenglesTextureFormat == key) { PlatformResult ret = SystemInfoDeviceCapability::GetOpenglesTextureFormat(value); @@ -203,7 +206,7 @@ static PlatformResult CheckStringCapability(const std::string& key, std::string* } static PlatformResult CheckBoolCapability(const std::string& key, bool* bool_value, bool* fetched) { - LoggerD("Entered CheckBoolCapability"); + ScopeLogger(); *fetched = false; if (kTizenFeatureBluetoothAlwaysOn == key) { *bool_value = SystemInfoDeviceCapability::IsBluetoothAlwaysOn(); @@ -233,7 +236,7 @@ static PlatformResult CheckBoolCapability(const std::string& key, bool* bool_val static PlatformResult CheckIntCapability(const std::string& key, std::string* value, bool* fetched) { - LoggerD("Entered CheckIntCapability"); + ScopeLogger(); int result = 0; if (key == kTizenFeatureCpuFrequency) { PlatformResult ret = SystemInfoDeviceCapability::GetPlatformCoreCpuFrequency(&result); @@ -260,7 +263,7 @@ static PlatformResult CheckIntCapability(const std::string& key, std::string* va PlatformResult SystemInfoDeviceCapability::GetCapability(const std::string& key, picojson::value* result) { - LoggerD("Entered"); + ScopeLogger(); picojson::object& result_obj = result->get(); std::string value = ""; @@ -305,6 +308,7 @@ PlatformResult SystemInfoDeviceCapability::GetCapability(const std::string& key, } PlatformResult SystemInfoDeviceCapability::IsInputKeyboardLayout(bool* result) { + ScopeLogger(); std::string input_keyboard_layout = ""; PlatformResult ret = GetValueString("tizen.org/feature/input.keyboard.layout", &input_keyboard_layout); @@ -329,6 +333,7 @@ PlatformResult SystemInfoDeviceCapability::IsInputKeyboardLayout(bool* result) { } PlatformResult SystemInfoDeviceCapability::GetOpenglesTextureFormat(std::string* result) { + ScopeLogger(); bool bool_result = false; PlatformResult ret = GetValueBool("tizen.org/feature/opengles", &bool_result); if (!bool_result) { @@ -411,6 +416,7 @@ PlatformResult SystemInfoDeviceCapability::GetOpenglesTextureFormat(std::string* } PlatformResult SystemInfoDeviceCapability::GetPlatfomCoreCpuArch(std::string* return_value) { + ScopeLogger(); std::string result; bool bool_result = false; std::string arch = ""; @@ -468,6 +474,7 @@ PlatformResult SystemInfoDeviceCapability::GetPlatfomCoreCpuArch(std::string* re } PlatformResult SystemInfoDeviceCapability::GetPlatfomCoreFpuArch(std::string* return_value) { + ScopeLogger(); std::string result; bool bool_result = false; PlatformResult ret = GetValueBool("tizen.org/feature/platform.core.fpu.arch.sse2", &bool_result); @@ -529,6 +536,7 @@ PlatformResult SystemInfoDeviceCapability::GetPlatfomCoreFpuArch(std::string* re } PlatformResult SystemInfoDeviceCapability::GetProfile(std::string* return_value) { + ScopeLogger(); std::string profile = ""; PlatformResult ret = GetValueString("tizen.org/feature/profile", &profile); if (ret.IsError()) { @@ -552,6 +560,7 @@ PlatformResult SystemInfoDeviceCapability::GetProfile(std::string* return_value) } bool SystemInfoDeviceCapability::IsBluetoothAlwaysOn() { + ScopeLogger(); #ifdef PROFILE_MOBILE_FULL return false; #elif PROFILE_MOBILE @@ -570,7 +579,7 @@ bool SystemInfoDeviceCapability::IsScreen() { } PlatformResult SystemInfoDeviceCapability::GetPlatformCoreCpuFrequency(int* return_value) { - LoggerD("Entered"); + ScopeLogger(); std::string freq; std::string file_name; @@ -613,17 +622,17 @@ PlatformResult SystemInfoDeviceCapability::GetPlatformCoreCpuFrequency(int* retu } PlatformResult SystemInfoDeviceCapability::IsNativeOspCompatible(bool* result) { - LoggerD("Enter"); + ScopeLogger(); return GetValueBool(kTizenFeaturePlatformNativeOspCompatible, result); } PlatformResult SystemInfoDeviceCapability::GetNativeAPIVersion(std::string* return_value) { - LoggerD("Enter"); + ScopeLogger(); return GetValueString(kTizenFeaturePlatformNativeApiVersion, return_value); } PlatformResult SystemInfoDeviceCapability::GetPlatformVersionName(std::string* result) { - LoggerD("Enter"); + ScopeLogger(); // Because of lack of 'http://tizen.org/feature/platform.version.name' // key on platform we use 'http://tizen.org/system/platform.name'. diff --git a/src/systeminfo/systeminfo_instance.cc b/src/systeminfo/systeminfo_instance.cc index 56cbc77..f8818d7 100644 --- a/src/systeminfo/systeminfo_instance.cc +++ b/src/systeminfo/systeminfo_instance.cc @@ -50,7 +50,7 @@ const std::string kPrivilegeLED = "http://tizen.org/privilege/led"; } SysteminfoInstance::SysteminfoInstance() : manager_(this) { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -75,11 +75,11 @@ SysteminfoInstance::SysteminfoInstance() : manager_(this) { } SysteminfoInstance::~SysteminfoInstance() { - LoggerD("Entered"); + ScopeLogger(); } void SysteminfoInstance::GetCapabilities(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); LoggerW( "DEPRECATION WARNING: getCapabilities() is deprecated and will be removed from next release. " "Use getCapability() instead."); @@ -88,49 +88,49 @@ void SysteminfoInstance::GetCapabilities(const picojson::value& args, picojson:: } void SysteminfoInstance::GetCapability(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.GetCapability(args, &out); } void SysteminfoInstance::GetPropertyValue(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.GetPropertyValue(args, &out); } void SysteminfoInstance::GetPropertyValueArray(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.GetPropertyValueArray(args, &out); } void SysteminfoInstance::AddPropertyValueChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.AddPropertyValueChangeListener(args, &out); } void SysteminfoInstance::RemovePropertyValueChangeListener(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.RemovePropertyValueChangeListener(args, &out); } void SysteminfoInstance::GetTotalMemory(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.GetTotalMemory(args, &out); } void SysteminfoInstance::GetAvailableMemory(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.GetAvailableMemory(args, &out); } void SysteminfoInstance::GetCount(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); manager_.GetCount(args, &out); } void SysteminfoInstance::SetBrightness(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeLED, &out); CHECK_EXIST(args, "brightness", out) @@ -154,7 +154,7 @@ void SysteminfoInstance::SetBrightness(const picojson::value& args, picojson::ob } void SysteminfoInstance::GetBrightness(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeLED, &out); int brightness = 0; @@ -170,7 +170,7 @@ void SysteminfoInstance::GetBrightness(const picojson::value& args, picojson::ob } void SysteminfoInstance::GetMaxBrightness(const picojson::value& args, picojson::object& out) { - LoggerD("entered"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeLED, &out); int brightness = 0; diff --git a/src/systeminfo/systeminfo_manager.cc b/src/systeminfo/systeminfo_manager.cc index d816bae..147b884 100644 --- a/src/systeminfo/systeminfo_manager.cc +++ b/src/systeminfo/systeminfo_manager.cc @@ -123,65 +123,65 @@ const std::string kPropertyIdCameraFlash = "CAMERA_FLASH"; // Callback static functions static void OnBatteryChangedCb(keynode_t* node, void* event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdBattery); } static gboolean OnCpuChangedCb(gpointer event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallCpuListenerCallback(); return G_SOURCE_CONTINUE; } static gboolean OnStorageChangedCb(gpointer event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallStorageListenerCallback(); return G_SOURCE_CONTINUE; } static void OnMmcChangedCb(keynode_t* node, void* event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdStorage); } static void OnDisplayChangedCb(keynode_t* node, void* event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdDisplay); } static void OnDeviceAutoRotationChangedCb(keynode_t* node, void* event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdDeviceOrientation); } static void OnDeviceOrientationChangedCb(sensor_t sensor, unsigned int event_type, sensor_data_t* data, void* user_data) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(user_data); manager->CallListenerCallback(kPropertyIdDeviceOrientation); } static void OnLocaleChangedCb(keynode_t* node, void* event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdLocale); } static void OnNetworkChangedCb(connection_type_e type, void* event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdNetwork); } static void OnNetworkValueChangedCb(const char* ipv4_address, const char* ipv6_address, void* event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdWifiNetwork); manager->CallListenerCallback(kPropertyIdEthernetNetwork); @@ -189,15 +189,14 @@ static void OnNetworkValueChangedCb(const char* ipv4_address, const char* ipv6_a } static void OnCellularNetworkValueChangedCb(keynode_t* node, void* event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdCellularNetwork, kDefaultListenerIndex); } static void OnTapiValueChangedCb(TapiHandle* handle, const char* noti_id, void* data, void* user_data) { - LoggerD("Enter"); - LoggerD("Changed key: %s", noti_id); + ScopeLogger("Changed key: %s", noti_id); SysteminfoManager* manager = static_cast(user_data); int index = manager->GetChangedTapiIndex(handle); LoggerD("Changed SIM index is: %d", index); @@ -205,19 +204,19 @@ static void OnTapiValueChangedCb(TapiHandle* handle, const char* noti_id, void* } static void OnPeripheralChangedCb(keynode_t* node, void* event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdPeripheral); } static void OnMemoryChangedCb(keynode_t* node, void* event_ptr) { - LoggerD("Enter"); + ScopeLogger(); SysteminfoManager* manager = static_cast(event_ptr); manager->CallListenerCallback(kPropertyIdMemory); } static void OnBrightnessChangedCb(device_callback_e type, void* value, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); if (type == DEVICE_CALLBACK_FLASH_BRIGHTNESS) { SysteminfoManager* manager = static_cast(user_data); manager->CallListenerCallback(kPropertyIdCameraFlash); @@ -225,7 +224,7 @@ static void OnBrightnessChangedCb(device_callback_e type, void* value, void* use } static void OnWifiLevelChangedCb(wifi_manager_rssi_level_e rssi_level, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); LoggerD("Level %d", rssi_level); SysteminfoManager* manager = static_cast(user_data); manager->SetWifiLevel(rssi_level); @@ -417,9 +416,11 @@ class SysteminfoManager::TapiManager { class SysteminfoManager::AsynchronousOperation { public: AsynchronousOperation(int count_ = 0) : count_(count_) { + ScopeLogger(); } ~AsynchronousOperation() { + ScopeLogger(); std::unique_lock lock(mutex_); while (0 != count_) { @@ -462,7 +463,7 @@ SysteminfoManager::SysteminfoManager(SysteminfoInstance* instance) storage_event_id_(0), connection_handle_(nullptr), async_op_(new AsynchronousOperation()) { - LoggerD("Entered"); + ScopeLogger(); int error = wifi_manager_initialize(&wifi_manager_); if (WIFI_MANAGER_ERROR_NONE != error) { @@ -482,7 +483,7 @@ SysteminfoManager::SysteminfoManager(SysteminfoInstance* instance) } SysteminfoManager::~SysteminfoManager() { - LoggerD("Enter"); + ScopeLogger(); DisconnectSensor(sensor_handle_); if (IsListenerRegistered(kPropertyIdBattery)) { @@ -541,7 +542,7 @@ SysteminfoManager::~SysteminfoManager() { } void SysteminfoManager::GetCapabilities(const picojson::value& args, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); @@ -635,7 +636,7 @@ void SysteminfoManager::GetCapabilities(const picojson::value& args, picojson::o } void SysteminfoManager::GetCapability(const picojson::value& args, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "key", out) const std::string& key = args.get("key").get(); LoggerD("Getting capability with key: %s ", key.c_str()); @@ -651,7 +652,7 @@ void SysteminfoManager::GetCapability(const picojson::value& args, picojson::obj } void SysteminfoManager::GetPropertyValue(const picojson::value& args, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "property", out) const double callback_id = args.get("callbackId").get(); @@ -660,7 +661,7 @@ void SysteminfoManager::GetPropertyValue(const picojson::value& args, picojson:: auto get = [this, prop_id, callback_id](const std::shared_ptr& response) -> void { - LoggerD("Getting"); + ScopeLogger("Entered into asynchronous function, get"); picojson::value result = picojson::value(picojson::object()); PlatformResult ret = prop_manager_.GetPropertyValue(prop_id, false, &result); async_op_->finish(); @@ -673,7 +674,7 @@ void SysteminfoManager::GetPropertyValue(const picojson::value& args, picojson:: auto get_response = [this, callback_id](const std::shared_ptr& response) -> void { - LoggerD("Getting response"); + ScopeLogger("Entered into asynchronous function, get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value{static_cast(callback_id)})); LoggerD("message: %s", response->serialize().c_str()); @@ -688,7 +689,7 @@ void SysteminfoManager::GetPropertyValue(const picojson::value& args, picojson:: } void SysteminfoManager::GetPropertyValueArray(const picojson::value& args, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "callbackId", out) CHECK_EXIST(args, "property", out) const double callback_id = args.get("callbackId").get(); @@ -697,7 +698,7 @@ void SysteminfoManager::GetPropertyValueArray(const picojson::value& args, picoj auto get = [this, prop_id, callback_id](const std::shared_ptr& response) -> void { - LoggerD("Getting"); + ScopeLogger("Entered into asynchronous function, get"); picojson::value result = picojson::value(picojson::object()); PlatformResult ret = prop_manager_.GetPropertyValue(prop_id, true, &result); @@ -711,7 +712,7 @@ void SysteminfoManager::GetPropertyValueArray(const picojson::value& args, picoj auto get_response = [this, callback_id](const std::shared_ptr& response) -> void { - LoggerD("Getting response"); + ScopeLogger("Entered into asynchronous function, get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(instance_, response->serialize().c_str()); @@ -725,7 +726,7 @@ void SysteminfoManager::GetPropertyValueArray(const picojson::value& args, picoj } void SysteminfoManager::GetTotalMemory(const picojson::value& args, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); @@ -743,7 +744,7 @@ void SysteminfoManager::GetTotalMemory(const picojson::value& args, picojson::ob } void SysteminfoManager::GetAvailableMemory(const picojson::value& args, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); @@ -761,7 +762,7 @@ void SysteminfoManager::GetAvailableMemory(const picojson::value& args, picojson } void SysteminfoManager::GetCount(const picojson::value& args, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_EXIST(args, "property", out) const std::string& property = args.get("property").get(); LoggerD("Getting count of property with id: %s ", property.c_str()); @@ -782,7 +783,7 @@ void SysteminfoManager::GetCount(const picojson::value& args, picojson::object* void SysteminfoManager::AddPropertyValueChangeListener(const picojson::value& args, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); // Check type of property for which listener should be registered CHECK_EXIST(args, "property", out) const std::string& property_name = args.get("property").get(); @@ -843,7 +844,7 @@ void SysteminfoManager::AddPropertyValueChangeListener(const picojson::value& ar void SysteminfoManager::RemovePropertyValueChangeListener(const picojson::value& args, picojson::object* out) { - LoggerD("Enter"); + ScopeLogger(); // Check type of property for which listener should be removed CHECK_EXIST(args, "property", out) @@ -909,14 +910,14 @@ void SysteminfoManager::RemovePropertyValueChangeListener(const picojson::value& } bool SysteminfoManager::IsIpChangeCallbackNotRegistered() { - LoggerD("Entered"); + ScopeLogger(); return !(IsListenerRegistered(kPropertyIdWifiNetwork) || IsListenerRegistered(kPropertyIdEthernetNetwork) || IsListenerRegistered(kPropertyIdCellularNetwork)); } PlatformResult SysteminfoManager::RegisterIpChangeCallback() { - LoggerD("Entered"); + ScopeLogger(); connection_h handle; PlatformResult ret(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR(GetConnectionHandle(handle)) @@ -931,7 +932,7 @@ PlatformResult SysteminfoManager::RegisterIpChangeCallback() { } PlatformResult SysteminfoManager::UnregisterIpChangeCallback() { - LoggerD("Entered"); + ScopeLogger(); connection_h handle; PlatformResult ret(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR(GetConnectionHandle(handle)) @@ -945,7 +946,7 @@ PlatformResult SysteminfoManager::UnregisterIpChangeCallback() { } PlatformResult SysteminfoManager::RegisterBatteryListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR(SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_BATTERY_CAPACITY, OnBatteryChangedCb, this)) @@ -956,7 +957,7 @@ PlatformResult SysteminfoManager::RegisterBatteryListener() { } PlatformResult SysteminfoManager::UnregisterBatteryListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR(SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SYSMAN_BATTERY_CAPACITY, OnBatteryChangedCb)) @@ -967,7 +968,7 @@ PlatformResult SysteminfoManager::UnregisterBatteryListener() { } PlatformResult SysteminfoManager::RegisterCpuListener() { - LoggerD("Entered"); + ScopeLogger(); cpu_event_id_ = g_timeout_add_seconds(kPropertyWatcherTime, OnCpuChangedCb, static_cast(this)); LoggerD("Added callback for CPU"); @@ -975,7 +976,7 @@ PlatformResult SysteminfoManager::RegisterCpuListener() { } PlatformResult SysteminfoManager::UnregisterCpuListener() { - LoggerD("Entered"); + ScopeLogger(); g_source_remove(cpu_event_id_); cpu_event_id_ = 0; LoggerD("Removed callback for CPU"); @@ -983,7 +984,7 @@ PlatformResult SysteminfoManager::UnregisterCpuListener() { } PlatformResult SysteminfoManager::RegisterStorageListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR( SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SYSMAN_MMC_STATUS, OnMmcChangedCb, this)) @@ -995,7 +996,7 @@ PlatformResult SysteminfoManager::RegisterStorageListener() { } PlatformResult SysteminfoManager::UnregisterStorageListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR( SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SYSMAN_MMC_STATUS, OnMmcChangedCb)) @@ -1007,7 +1008,7 @@ PlatformResult SysteminfoManager::UnregisterStorageListener() { } PlatformResult SysteminfoManager::RegisterDisplayListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR(SysteminfoUtils::RegisterVconfCallback(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, OnDisplayChangedCb, this)) @@ -1016,7 +1017,7 @@ PlatformResult SysteminfoManager::RegisterDisplayListener() { } PlatformResult SysteminfoManager::UnregisterDisplayListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR( SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, OnDisplayChangedCb)) @@ -1025,7 +1026,7 @@ PlatformResult SysteminfoManager::UnregisterDisplayListener() { } PlatformResult SysteminfoManager::RegisterDeviceOrientationListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR(SysteminfoUtils::RegisterVconfCallback( VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, OnDeviceAutoRotationChangedCb, this)) @@ -1044,7 +1045,7 @@ PlatformResult SysteminfoManager::RegisterDeviceOrientationListener() { } PlatformResult SysteminfoManager::UnregisterDeviceOrientationListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR(SysteminfoUtils::UnregisterVconfCallback( VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, OnDeviceAutoRotationChangedCb)) @@ -1060,7 +1061,7 @@ PlatformResult SysteminfoManager::UnregisterDeviceOrientationListener() { } PlatformResult SysteminfoManager::RegisterLocaleListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR( SysteminfoUtils::RegisterVconfCallback(VCONFKEY_REGIONFORMAT, OnLocaleChangedCb, this)) @@ -1071,7 +1072,7 @@ PlatformResult SysteminfoManager::RegisterLocaleListener() { } PlatformResult SysteminfoManager::UnregisterLocaleListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR( SysteminfoUtils::UnregisterVconfCallback(VCONFKEY_REGIONFORMAT, OnLocaleChangedCb)) @@ -1083,7 +1084,7 @@ PlatformResult SysteminfoManager::UnregisterLocaleListener() { } PlatformResult SysteminfoManager::RegisterNetworkListener() { - LoggerD("Entered"); + ScopeLogger(); connection_h handle; PlatformResult ret(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR(GetConnectionHandle(handle)) @@ -1099,7 +1100,7 @@ PlatformResult SysteminfoManager::RegisterNetworkListener() { } PlatformResult SysteminfoManager::UnregisterNetworkListener() { - LoggerD("Entered"); + ScopeLogger(); connection_h handle; PlatformResult ret(ErrorCode::NO_ERROR); CHECK_LISTENER_ERROR(GetConnectionHandle(handle)) @@ -1114,7 +1115,7 @@ PlatformResult SysteminfoManager::UnregisterNetworkListener() { } PlatformResult SysteminfoManager::RegisterWifiNetworkListener() { - LoggerD("Entered"); + ScopeLogger(); if (IsIpChangeCallbackNotRegistered()) { PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); @@ -1127,7 +1128,7 @@ PlatformResult SysteminfoManager::RegisterWifiNetworkListener() { } PlatformResult SysteminfoManager::UnregisterWifiNetworkListener() { - LoggerD("Entered"); + ScopeLogger(); // if there is no other ip-relateded listeners left, unregister if (IsIpChangeCallbackNotRegistered()) { PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); @@ -1141,7 +1142,7 @@ PlatformResult SysteminfoManager::UnregisterWifiNetworkListener() { } PlatformResult SysteminfoManager::RegisterEthernetNetworkListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = SysteminfoUtils::CheckIfEthernetNetworkSupported(); if (ret.IsError()) { return ret; @@ -1159,7 +1160,7 @@ PlatformResult SysteminfoManager::RegisterEthernetNetworkListener() { } PlatformResult SysteminfoManager::UnregisterEthernetNetworkListener() { - LoggerD("Entered"); + ScopeLogger(); if (IsIpChangeCallbackNotRegistered()) { PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); @@ -1173,7 +1174,7 @@ PlatformResult SysteminfoManager::UnregisterEthernetNetworkListener() { } PlatformResult SysteminfoManager::RegisterCellularNetworkListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = SysteminfoUtils::CheckTelephonySupport(); if (ret.IsError()) { return ret; @@ -1198,7 +1199,7 @@ PlatformResult SysteminfoManager::RegisterCellularNetworkListener() { } PlatformResult SysteminfoManager::UnregisterCellularNetworkListener() { - LoggerD("Entered"); + ScopeLogger(); // if there is no other ip-relateded listeners left, unregister if (!IsListenerRegistered(kPropertyIdCellularNetwork)) { @@ -1221,7 +1222,7 @@ PlatformResult SysteminfoManager::UnregisterCellularNetworkListener() { } PlatformResult SysteminfoManager::RegisterPeripheralListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); int value = 0; /* if (-1 != vconf_get_int(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, &value)) { @@ -1238,7 +1239,7 @@ PlatformResult SysteminfoManager::RegisterPeripheralListener() { } PlatformResult SysteminfoManager::UnregisterPeripheralListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); int value = 0; /* if (-1 != vconf_get_int(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, &value)) { @@ -1255,7 +1256,7 @@ PlatformResult SysteminfoManager::UnregisterPeripheralListener() { } PlatformResult SysteminfoManager::RegisterMemoryListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); int value = 0; if (-1 != vconf_get_int(VCONFKEY_SYSMAN_LOW_MEMORY, &value)) { @@ -1267,7 +1268,7 @@ PlatformResult SysteminfoManager::RegisterMemoryListener() { } PlatformResult SysteminfoManager::UnregisterMemoryListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); int value = 0; if (-1 != vconf_get_int(VCONFKEY_SYSMAN_LOW_MEMORY, &value)) { @@ -1279,7 +1280,7 @@ PlatformResult SysteminfoManager::UnregisterMemoryListener() { } PlatformResult SysteminfoManager::RegisterCameraFlashListener() { - LoggerD("Entered"); + ScopeLogger(); int ret = device_add_callback(DEVICE_CALLBACK_FLASH_BRIGHTNESS, OnBrightnessChangedCb, this); if (DEVICE_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Error occured", @@ -1289,7 +1290,7 @@ PlatformResult SysteminfoManager::RegisterCameraFlashListener() { } PlatformResult SysteminfoManager::UnregisterCameraFlashListener() { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = PlatformResult(ErrorCode::NO_ERROR); int ntv_ret = device_remove_callback(DEVICE_CALLBACK_FLASH_BRIGHTNESS, OnBrightnessChangedCb); if (DEVICE_ERROR_NONE != ntv_ret) { @@ -1302,7 +1303,7 @@ PlatformResult SysteminfoManager::UnregisterCameraFlashListener() { } void SysteminfoManager::SetBrightness(const picojson::value& args, picojson::object* out) { - LoggerD("entered"); + ScopeLogger(); CHECK_EXIST(args, "brightness", out) @@ -1318,7 +1319,7 @@ void SysteminfoManager::SetBrightness(const picojson::value& args, picojson::obj } void SysteminfoManager::GetBrightness(const picojson::value& args, picojson::object* out) { - LoggerD("entered"); + ScopeLogger(); int brightness = 0; int result = device_flash_get_brightness(&brightness); @@ -1332,7 +1333,7 @@ void SysteminfoManager::GetBrightness(const picojson::value& args, picojson::obj } void SysteminfoManager::GetMaxBrightness(const picojson::value& args, picojson::object* out) { - LoggerD("entered"); + ScopeLogger(); int brightness = 0; int result = device_flash_get_max_brightness(&brightness); @@ -1347,7 +1348,7 @@ void SysteminfoManager::GetMaxBrightness(const picojson::value& args, picojson:: PlatformResult SysteminfoManager::GetPropertyCount(const std::string& property, unsigned long* count) { - LoggerD("Enter"); + ScopeLogger(); if ("BATTERY" == property || "CPU" == property || "STORAGE" == property || "DISPLAY" == property || "DEVICE_ORIENTATION" == property || "BUILD" == property || @@ -1379,17 +1380,17 @@ PlatformResult SysteminfoManager::GetPropertyCount(const std::string& property, } wifi_manager_rssi_level_e SysteminfoManager::GetWifiLevel() { - LoggerD("Enter"); + ScopeLogger(); return wifi_level_; } void SysteminfoManager::SetWifiLevel(wifi_manager_rssi_level_e level) { - LoggerD("Entered"); + ScopeLogger(); wifi_level_ = level; } int SysteminfoManager::GetSensorHandle() { - LoggerD("Enter"); + ScopeLogger(); std::lock_guard lock(sensor_mutex_); if (sensor_handle_ < 0) { LoggerD("Connecting to sensor"); @@ -1401,7 +1402,7 @@ int SysteminfoManager::GetSensorHandle() { } PlatformResult SysteminfoManager::ConnectSensor(int* result) { - LoggerD("Entered"); + ScopeLogger(); sensor_t sensor = sensord_get_sensor(AUTO_ROTATION_SENSOR); int handle_orientation = sensord_connect(sensor); if (handle_orientation < 0) { @@ -1420,9 +1421,9 @@ PlatformResult SysteminfoManager::ConnectSensor(int* result) { } void SysteminfoManager::DisconnectSensor(int handle_orientation) { - LoggerD("Enter"); + ScopeLogger(); if (handle_orientation >= 0) { - LoggerD("Entered"); + ScopeLogger(); bool state = sensord_stop(handle_orientation); LoggerD("sensord_stop() returned state = %d", state); state = sensord_disconnect(handle_orientation); @@ -1433,17 +1434,17 @@ void SysteminfoManager::DisconnectSensor(int handle_orientation) { } void SysteminfoManager::SetCpuInfoLoad(double load) { - LoggerD("Enter"); + ScopeLogger(); cpu_load_ = load; } void SysteminfoManager::SetAvailableCapacityInternal(unsigned long long capacity) { - LoggerD("Entered"); + ScopeLogger(); available_capacity_internal_ = capacity; } void SysteminfoManager::SetAvailableCapacityMmc(unsigned long long capacity) { - LoggerD("Entered"); + ScopeLogger(); available_capacity_mmc_ = capacity; } @@ -1473,7 +1474,7 @@ PlatformResult SysteminfoManager::FetchBasicSimProperties( } void SysteminfoManager::InitCameraTypes() { - LoggerD("Enter"); + ScopeLogger(); bool supported = false; PlatformResult ret = SystemInfoDeviceCapability::GetValueBool("tizen.org/feature/camera.back.flash", &supported); @@ -1492,7 +1493,7 @@ void SysteminfoManager::InitCameraTypes() { } std::string SysteminfoManager::GetCameraTypes(unsigned int index) { - LoggerD("Enter"); + ScopeLogger(); if (index >= camera_types_.size()) { return ""; } @@ -1500,12 +1501,12 @@ std::string SysteminfoManager::GetCameraTypes(unsigned int index) { } unsigned int SysteminfoManager::GetCameraTypesCount() { - LoggerD("Enter"); + ScopeLogger(); return camera_types_.size(); } PlatformResult SysteminfoManager::GetConnectionHandle(connection_h& handle) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(connection_mutex_); if (nullptr == connection_handle_) { int error = connection_create(&connection_handle_); @@ -1520,13 +1521,13 @@ PlatformResult SysteminfoManager::GetConnectionHandle(connection_h& handle) { } bool SysteminfoManager::IsListenerRegistered(const std::string& property_id) { - LoggerD("Entered"); + ScopeLogger(); return (registered_listeners_.find(property_id) != registered_listeners_.end()); } void SysteminfoManager::PostListenerResponse(const std::string& property_id, const picojson::value& result, int property_index) { - LoggerD("Entered"); + ScopeLogger(); const std::shared_ptr& response = std::shared_ptr(new picojson::value(picojson::object())); response->get()[kPropertyIdString] = picojson::value(property_id); @@ -1540,7 +1541,7 @@ void SysteminfoManager::PostListenerResponse(const std::string& property_id, } void SysteminfoManager::CallListenerCallback(const std::string& property_id, int property_index) { - LoggerD("Enter"); + ScopeLogger(); if (IsListenerRegistered(property_id)) { LoggerD("listener for %s property is registered, calling it", property_id.c_str()); @@ -1555,7 +1556,7 @@ void SysteminfoManager::CallListenerCallback(const std::string& property_id, int } void SysteminfoManager::CallCpuListenerCallback() { - LoggerD("Enter"); + ScopeLogger(); std::string property_id = kPropertyIdCpu; if (IsListenerRegistered(property_id)) { LoggerD("listener for %s property is registered, calling it", property_id.c_str()); @@ -1575,7 +1576,7 @@ void SysteminfoManager::CallCpuListenerCallback() { } void SysteminfoManager::CallStorageListenerCallback() { - LoggerD("Enter"); + ScopeLogger(); std::string property_id = kPropertyIdStorage; if (IsListenerRegistered(property_id)) { LoggerD("listener for %s property is registered, calling it", property_id.c_str()); diff --git a/src/systeminfo/systeminfo_properties_manager.cc b/src/systeminfo/systeminfo_properties_manager.cc index 5a495b5..1868a24 100644 --- a/src/systeminfo/systeminfo_properties_manager.cc +++ b/src/systeminfo/systeminfo_properties_manager.cc @@ -97,17 +97,17 @@ const char* kConnectionOn = "ON"; SysteminfoPropertiesManager::SysteminfoPropertiesManager(SysteminfoManager& manager) : manager_(manager) { - LoggerD("Entered"); + ScopeLogger(); } SysteminfoPropertiesManager::~SysteminfoPropertiesManager() { - LoggerD("Entered"); + ScopeLogger(); } PlatformResult SysteminfoPropertiesManager::GetPropertyValue(const std::string& property, bool is_array_type, picojson::value* res) { - LoggerD("Entered getPropertyValue"); + ScopeLogger(); if (!is_array_type) { picojson::object& res_obj = res->get(); @@ -148,7 +148,7 @@ PlatformResult SysteminfoPropertiesManager::GetPropertyValue(const std::string& PlatformResult SysteminfoPropertiesManager::ReportProperty(const std::string& property, int index, picojson::object* res_obj) { - LoggerD("Entered"); + ScopeLogger(); if ("BATTERY" == property) { return ReportBattery(res_obj); } else if ("CPU" == property) { @@ -190,7 +190,7 @@ PlatformResult SysteminfoPropertiesManager::ReportProperty(const std::string& pr /// BATTERY PlatformResult SysteminfoPropertiesManager::ReportBattery(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); int value = 0; int ret = vconf_get_int(VCONFKEY_SYSMAN_BATTERY_CAPACITY, &value); if (kVconfErrorNone != ret) { @@ -214,7 +214,7 @@ PlatformResult SysteminfoPropertiesManager::ReportBattery(picojson::object* out) /// CPU PlatformResult SysteminfoPropertiesManager::ReportCpu(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); static CpuInfo cpu_info; FILE* fp = nullptr; fp = fopen("/proc/stat", "r"); @@ -262,7 +262,7 @@ PlatformResult SysteminfoPropertiesManager::ReportCpu(picojson::object* out) { /// DISPLAY PlatformResult SysteminfoPropertiesManager::ReportDisplay(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); int screenWidth = 0; int screenHeight = 0; int dotsPerInchWidth = 0; @@ -342,7 +342,7 @@ PlatformResult SysteminfoPropertiesManager::ReportDisplay(picojson::object* out) /// DEVICE_ORIENTATION PlatformResult SysteminfoPropertiesManager::FetchIsAutoRotation(bool* result) { - LoggerD("Entered"); + ScopeLogger(); int is_auto_rotation = 0; if (0 == vconf_get_bool(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, &is_auto_rotation)) { @@ -359,7 +359,7 @@ PlatformResult SysteminfoPropertiesManager::FetchIsAutoRotation(bool* result) { } PlatformResult SysteminfoPropertiesManager::FetchStatus(std::string* result) { - LoggerD("Entered"); + ScopeLogger(); int rotation = 0; std::string status = kOrientationPortraitPrimary; @@ -404,7 +404,7 @@ PlatformResult SysteminfoPropertiesManager::FetchStatus(std::string* result) { } PlatformResult SysteminfoPropertiesManager::ReportDeviceOrientation(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); bool is_auto_rotation = false; std::string status = ""; @@ -421,7 +421,7 @@ PlatformResult SysteminfoPropertiesManager::ReportDeviceOrientation(picojson::ob /// BUILD PlatformResult SysteminfoPropertiesManager::ReportBuild(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); std::string model = ""; PlatformResult ret = SystemInfoDeviceCapability::GetValueString("tizen.org/system/model_name", &model); @@ -447,7 +447,7 @@ PlatformResult SysteminfoPropertiesManager::ReportBuild(picojson::object* out) { /// LOCALE PlatformResult SysteminfoPropertiesManager::ReportLocale(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); std::string str_language = ""; PlatformResult ret = SysteminfoUtils::GetRuntimeInfoString(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &str_language); @@ -468,7 +468,7 @@ PlatformResult SysteminfoPropertiesManager::ReportLocale(picojson::object* out) /// NETWORK static PlatformResult GetNetworkTypeString(NetworkType type, std::string& type_string) { - LoggerD("Entered"); + ScopeLogger(); switch (type) { case kNone: type_string = kNetworkTypeNone; @@ -506,7 +506,7 @@ static PlatformResult GetNetworkTypeString(NetworkType type, std::string& type_s PlatformResult SysteminfoPropertiesManager::ReportNetwork(picojson::object* out, unsigned long count) { - LoggerD("Entered with index property %d", count); + ScopeLogger("index property %d", count); connection_h connection_handle = nullptr; connection_type_e connection_type = CONNECTION_TYPE_DISCONNECTED; int networkType = 0; @@ -579,7 +579,7 @@ PlatformResult SysteminfoPropertiesManager::ReportNetwork(picojson::object* out, /// WIFI_NETWORK static PlatformResult GetIpsWifi(wifi_manager_ap_h wifi_ap_handle, std::string* ip_addr_str, std::string* ipv6_addr_str) { - LoggerD("Entered"); + ScopeLogger(); // getting ipv4 address char* ip_addr = nullptr; int error = @@ -609,7 +609,7 @@ static PlatformResult GetIpsWifi(wifi_manager_ap_h wifi_ap_handle, std::string* /// CELLULAR_NETWORK and ETHERNET_NETWORK static PlatformResult GetIpsFromProfile(connection_profile_h profile_handle, std::string* ip_addr_str, std::string* ipv6_addr_str) { - LoggerD("Entered"); + ScopeLogger(); // getting ipv4 address char* ip_addr = nullptr; int error = @@ -639,7 +639,7 @@ static PlatformResult GetIpsFromProfile(connection_profile_h profile_handle, } PlatformResult SysteminfoPropertiesManager::ReportWifiNetwork(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); bool result_status = false; std::string result_ssid; @@ -773,7 +773,7 @@ PlatformResult SysteminfoPropertiesManager::ReportWifiNetwork(picojson::object* /// ETHERNET_NETWORK PlatformResult SysteminfoPropertiesManager::ReportEthernetNetwork(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); std::string result_cable; std::string result_status; @@ -908,7 +908,7 @@ PlatformResult SysteminfoPropertiesManager::ReportEthernetNetwork(picojson::obje static PlatformResult FetchConnection(std::string* result_status, std::string* result_apn, std::string* result_ip_address, std::string* result_ipv6_address) { - LoggerD("Entered"); + ScopeLogger(); connection_type_e connection_type = CONNECTION_TYPE_DISCONNECTED; connection_profile_h profile_handle = nullptr; connection_h connection_handle = nullptr; @@ -986,7 +986,7 @@ static PlatformResult FetchConnection(std::string* result_status, std::string* r PlatformResult SysteminfoPropertiesManager::ReportCellularNetwork(picojson::object* out, unsigned long count) { - LoggerD("Entered with index property %d", count); + ScopeLogger("index property %lu", count); PlatformResult ret = SysteminfoUtils::CheckTelephonySupport(); if (ret.IsError()) { return ret; @@ -1032,7 +1032,7 @@ PlatformResult SysteminfoPropertiesManager::ReportCellularNetwork(picojson::obje /// NET_PROXY_NETWORK PlatformResult SysteminfoPropertiesManager::ReportNetProxyNetwork(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); connection_type_e connection_type = CONNECTION_TYPE_DISCONNECTED; connection_h connection_handle = nullptr; std::string result_status; @@ -1068,7 +1068,7 @@ PlatformResult SysteminfoPropertiesManager::ReportNetProxyNetwork(picojson::obje /// SIM PlatformResult SysteminfoPropertiesManager::ReportSim(picojson::object* out, unsigned long count) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult ret = SysteminfoUtils::CheckTelephonySupport(); if (ret.IsError()) { return ret; @@ -1078,7 +1078,7 @@ PlatformResult SysteminfoPropertiesManager::ReportSim(picojson::object* out, uns /// PERIPHERAL PlatformResult SysteminfoPropertiesManager::ReportPeripheral(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); /* int wireless_display_status = 0; PlatformResult ret = GetVconfInt(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, &wireless_display_status); if (ret.IsSuccess()) { @@ -1102,7 +1102,7 @@ PlatformResult SysteminfoPropertiesManager::ReportPeripheral(picojson::object* o /// MEMORY PlatformResult SysteminfoPropertiesManager::ReportMemory(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); std::string state = kMemoryStateNormal; int status = 0; PlatformResult ret = SysteminfoUtils::GetVconfInt(VCONFKEY_SYSMAN_LOW_MEMORY, &status); @@ -1123,7 +1123,7 @@ PlatformResult SysteminfoPropertiesManager::ReportMemory(picojson::object* out) } static void CreateStorageInfo(const std::string& type, struct statvfs& fs, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); out->insert(std::make_pair("type", picojson::value(type))); out->insert(std::make_pair( "capacity", picojson::value(std::to_string(static_cast(fs.f_frsize) * @@ -1152,7 +1152,7 @@ static std::string FromStorageTypeToStringType(common::StorageType type) { } PlatformResult SysteminfoPropertiesManager::ReportStorage(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); struct statvfs fs; picojson::value result = picojson::value(picojson::array()); @@ -1191,7 +1191,7 @@ PlatformResult SysteminfoPropertiesManager::ReportStorage(picojson::object* out) PlatformResult SysteminfoPropertiesManager::ReportCameraFlash(picojson::object* out, unsigned long index) { - LoggerD("Entered"); + ScopeLogger(); if (index < manager_.GetCameraTypesCount()) { std::string camera = manager_.GetCameraTypes(index); out->insert(std::make_pair("camera", picojson::value(camera))); @@ -1205,7 +1205,7 @@ PlatformResult SysteminfoPropertiesManager::ReportCameraFlash(picojson::object* /// ADS PlatformResult SysteminfoPropertiesManager::ReportAds(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); std::string ads_id = ""; PlatformResult ret = SysteminfoUtils::GetRuntimeInfoString(SYSTEM_SETTINGS_KEY_ADS_ID, &ads_id); if (ret.IsError()) { diff --git a/src/systeminfo/systeminfo_sim_details_manager.cc b/src/systeminfo/systeminfo_sim_details_manager.cc index 0ad13fc..3fb1c22 100644 --- a/src/systeminfo/systeminfo_sim_details_manager.cc +++ b/src/systeminfo/systeminfo_sim_details_manager.cc @@ -35,7 +35,7 @@ const char* kSimStatusNetworkLocked = "NETWORK_LOCKED"; const char* kSimStatusUnknown = "UNKNOWN"; void SimCphsValueCallback(TapiHandle* /*handle*/, int result, void* data, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); SimDetailsManager* sim_mgr = static_cast(user_data); TelSimAccessResult_t access_rt = static_cast(result); TelSimCphsNetName_t* cphs_info = static_cast(data); @@ -56,7 +56,7 @@ void SimCphsValueCallback(TapiHandle* /*handle*/, int result, void* data, void* } void SimMsisdnValueCallback(TapiHandle* /*handle*/, int result, void* data, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); SimDetailsManager* sim_mgr = static_cast(user_data); TelSimAccessResult_t access_rt = static_cast(result); TelSimMsisdnList_t* msisdn_info = static_cast(data); @@ -81,7 +81,7 @@ void SimMsisdnValueCallback(TapiHandle* /*handle*/, int result, void* data, void } void SimSpnValueCallback(TapiHandle* /*handle*/, int result, void* data, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); SimDetailsManager* sim_mgr = static_cast(user_data); TelSimAccessResult_t access_rt = static_cast(result); TelSimSpn_t* spn_info = static_cast(data); @@ -98,7 +98,7 @@ void SimSpnValueCallback(TapiHandle* /*handle*/, int result, void* data, void* u } void SimIccidValueCallback(TapiHandle* /*handle*/, int result, void* data, void* user_data) { - LoggerD("Entered"); + ScopeLogger(); SimDetailsManager* sim_mgr = static_cast(user_data); TelSimAccessResult_t access_rt = static_cast(result); TelSimIccIdInfo_t* iccid_info = static_cast(data); @@ -132,10 +132,11 @@ SimDetailsManager::SimDetailsManager() spn_(""), sim_result_obj_(nullptr), to_process_(0) { + ScopeLogger(); } PlatformResult SimDetailsManager::GatherSimInformation(TapiHandle* handle, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard first_lock_sim(sim_info_mutex_); ResetSimHolder(out); @@ -243,7 +244,7 @@ PlatformResult SimDetailsManager::FetchBasicSimProperties( } void SimDetailsManager::FetchSimState(TapiHandle* tapi_handle) { - LoggerD("Entered"); + ScopeLogger(); if (nullptr == tapi_handle) { LoggerE("Tapi handle is null"); state_ = kSimStatusUnknown; @@ -286,7 +287,7 @@ void SimDetailsManager::FetchSimState(TapiHandle* tapi_handle) { } PlatformResult SimDetailsManager::FetchSimSyncProps(TapiHandle* tapi_handle) { - LoggerD("Entered"); + ScopeLogger(); TelSimImsiInfo_t imsi; int error = tel_get_sim_imsi(tapi_handle, &imsi); if (TAPI_API_SUCCESS == error) { @@ -303,7 +304,7 @@ PlatformResult SimDetailsManager::FetchSimSyncProps(TapiHandle* tapi_handle) { } void SimDetailsManager::ResetSimHolder(picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); sim_result_obj_ = out; to_process_ = 0; mcc_ = 0; @@ -317,7 +318,7 @@ void SimDetailsManager::ResetSimHolder(picojson::object* out) { } void SimDetailsManager::ReturnSimToJS() { - LoggerD("Entered"); + ScopeLogger(); if (nullptr != sim_result_obj_) { sim_result_obj_->insert(std::make_pair("state", picojson::value(state_))); sim_result_obj_->insert(std::make_pair("operatorName", picojson::value(operator_name_))); @@ -335,7 +336,7 @@ void SimDetailsManager::ReturnSimToJS() { } void SimDetailsManager::TryReturn() { - LoggerD("Entered"); + ScopeLogger(); if (0 == to_process_) { LoggerD("Returning property to JS"); ReturnSimToJS(); @@ -346,7 +347,7 @@ void SimDetailsManager::TryReturn() { } void SimDetailsManager::set_operator_name(const std::string& name) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(sim_to_process_mutex_); operator_name_ = name; --to_process_; @@ -354,7 +355,7 @@ void SimDetailsManager::set_operator_name(const std::string& name) { }; void SimDetailsManager::set_msisdn(const std::string& msisdn) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(sim_to_process_mutex_); this->msisdn_ = msisdn; --to_process_; @@ -362,7 +363,7 @@ void SimDetailsManager::set_msisdn(const std::string& msisdn) { }; void SimDetailsManager::set_spn(const std::string& spn) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(sim_to_process_mutex_); this->spn_ = spn; --to_process_; @@ -370,7 +371,7 @@ void SimDetailsManager::set_spn(const std::string& spn) { }; void SimDetailsManager::set_iccid(const std::string& iccid) { - LoggerD("Entered"); + ScopeLogger(); std::lock_guard lock(sim_to_process_mutex_); this->iccid_ = iccid; --to_process_; diff --git a/src/systemsetting/systemsetting_instance.cc b/src/systemsetting/systemsetting_instance.cc index 64fb7d3..8b28ba7 100644 --- a/src/systemsetting/systemsetting_instance.cc +++ b/src/systemsetting/systemsetting_instance.cc @@ -42,7 +42,7 @@ using namespace common; using namespace extension::systemsetting; SystemSettingInstance::SystemSettingInstance() { - LoggerD("Enter"); + ScopeLogger(); using std::placeholders::_1; using std::placeholders::_2; @@ -55,18 +55,18 @@ SystemSettingInstance::SystemSettingInstance() { } SystemSettingInstance::~SystemSettingInstance() { - LoggerD("Enter"); + ScopeLogger(); } void SystemSettingInstance::getProperty(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); const double callback_id = args.get("callbackId").get(); const std::string& type = args.get("type").get(); LoggerD("Getting property type: %s ", type.c_str()); auto get = [this, type](const std::shared_ptr& response) -> void { - LoggerD("Getting platform value"); + ScopeLogger("Entered into asynchronous function, get"); picojson::value result = picojson::value(picojson::object()); PlatformResult status = getPlatformPropertyValue(type, &result); if (status.IsSuccess()) { @@ -79,7 +79,7 @@ void SystemSettingInstance::getProperty(const picojson::value& args, picojson::o auto get_response = [this, callback_id](const std::shared_ptr& response) -> void { - LoggerD("Getting response"); + ScopeLogger("Entered into asynchronous function, get_response"); picojson::object& obj = response->get(); obj.insert(std::make_pair("callbackId", picojson::value(callback_id))); Instance::PostMessage(this, response->serialize().c_str()); @@ -92,7 +92,7 @@ void SystemSettingInstance::getProperty(const picojson::value& args, picojson::o PlatformResult SystemSettingInstance::getPlatformPropertyValue(const std::string& settingType, picojson::value* out) { - LoggerD("Enter"); + ScopeLogger(); picojson::object& result_obj = out->get(); int ret = SYSTEM_SETTINGS_ERROR_INVALID_PARAMETER; @@ -125,7 +125,7 @@ PlatformResult SystemSettingInstance::getPlatformPropertyValue(const std::string } void SystemSettingInstance::setProperty(const picojson::value& args, picojson::object& out) { - LoggerD("Enter"); + ScopeLogger(); CHECK_PRIVILEGE_ACCESS(kPrivilegeSetting, &out); @@ -139,7 +139,7 @@ void SystemSettingInstance::setProperty(const picojson::value& args, picojson::o auto get = [this, type, value, callback_id](const std::shared_ptr& response) -> void { - LoggerD("Setting platform value"); + ScopeLogger("Entered into asynchronous function, get"); std::string real_path = common::FilesystemProvider::Create().GetRealPath(value); PlatformResult status = setPlatformPropertyValue(type, real_path); picojson::object& obj = response->get(); @@ -159,7 +159,7 @@ void SystemSettingInstance::setProperty(const picojson::value& args, picojson::o PlatformResult SystemSettingInstance::setPlatformPropertyValue(const std::string& settingType, const std::string& settingValue) { - LoggerD("Enter"); + ScopeLogger(); int ret = SYSTEM_SETTINGS_ERROR_INVALID_PARAMETER; if (settingType == SETTING_HOME_SCREEN) { ret = system_settings_set_value_string(SYSTEM_SETTINGS_KEY_WALLPAPER_HOME_SCREEN, diff --git a/src/time/time_extension.cc b/src/time/time_extension.cc index 769a6f4..607347d 100644 --- a/src/time/time_extension.cc +++ b/src/time/time_extension.cc @@ -8,7 +8,7 @@ #include "time/time_instance.h" common::Extension* CreateExtension() { - LoggerD("Entered"); + ScopeLogger(); return new TimeExtension; } @@ -16,7 +16,7 @@ common::Extension* CreateExtension() { extern const char kSource_time_api[]; TimeExtension::TimeExtension() { - LoggerD("Entered"); + ScopeLogger(); SetExtensionName("tizen.time"); SetJavaScriptAPI(kSource_time_api); @@ -25,10 +25,10 @@ TimeExtension::TimeExtension() { } TimeExtension::~TimeExtension() { - LoggerD("Entered"); + ScopeLogger(); } common::Instance* TimeExtension::CreateInstance() { - LoggerD("Entered"); + ScopeLogger(); return new extension::time::TimeInstance(); } diff --git a/src/time/time_instance.cc b/src/time/time_instance.cc index 5fc4db0..5ef0a2a 100644 --- a/src/time/time_instance.cc +++ b/src/time/time_instance.cc @@ -17,7 +17,7 @@ TimeInstance::TimeInstance() : manager_(this) { using std::placeholders::_1; using std::placeholders::_2; - LoggerD("Entered"); + ScopeLogger(); #define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&TimeInstance::x, this, _1, _2)); #define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&TimeInstance::x, this, _1, _2)); @@ -47,12 +47,12 @@ TimeInstance::TimeInstance() : manager_(this) { } TimeInstance::~TimeInstance() { - LoggerD("Entered"); + ScopeLogger(); } void TimeInstance::TimeUtil_getAvailableTimezones(const picojson::value& /*args*/, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); picojson::value result = picojson::value(picojson::object()); picojson::object& result_obj = result.get(); @@ -68,7 +68,7 @@ void TimeInstance::TimeUtil_getAvailableTimezones(const picojson::value& /*args* } void TimeInstance::TimeUtil_getDateFormat(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); if (!args.contains("shortformat")) { LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out, ("Required parameter \"shortformat\" is missing")); @@ -92,7 +92,7 @@ void TimeInstance::TimeUtil_getDateFormat(const picojson::value& args, picojson: void TimeInstance::TimeUtil_getTimeFormat(const picojson::value& /* args */, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); std::string format; PlatformResult res = TimeUtilTools::GetTimeFormat(&format); if (res.IsError()) { @@ -109,7 +109,7 @@ void TimeInstance::TimeUtil_getTimeFormat(const picojson::value& /* args */, void TimeInstance::TimeUtil_setDateTimeChangeListener(const picojson::value& /*args*/, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult res = manager_.RegisterVconfCallback(kTimeChange); if (res.IsError()) { LogAndReportError(res, &out, ("Failed to set date-time change listener.")); @@ -119,7 +119,7 @@ void TimeInstance::TimeUtil_setDateTimeChangeListener(const picojson::value& /*a void TimeInstance::TimeUtil_unsetDateTimeChangeListener(const picojson::value& /*args*/, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult res = manager_.UnregisterVconfCallback(kTimeChange); if (res.IsError()) { LogAndReportError(res, &out, ("Failed to remove date-time change listener.")); @@ -129,7 +129,7 @@ void TimeInstance::TimeUtil_unsetDateTimeChangeListener(const picojson::value& / void TimeInstance::TimeUtil_setTimezoneChangeListener(const picojson::value& /*args*/, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult res = manager_.RegisterVconfCallback(kTimezoneChange); if (res.IsError()) { LogAndReportError(res, &out, ("Failed to set timezone change listener.")); @@ -139,7 +139,7 @@ void TimeInstance::TimeUtil_setTimezoneChangeListener(const picojson::value& /*a void TimeInstance::TimeUtil_unsetTimezoneChangeListener(const picojson::value& /*args*/, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); PlatformResult res = manager_.UnregisterVconfCallback(kTimezoneChange); if (res.IsError()) { LogAndReportError(res, &out, ("Failed to remove timezone change listener.")); @@ -148,7 +148,7 @@ void TimeInstance::TimeUtil_unsetTimezoneChangeListener(const picojson::value& / } void TimeInstance::TZDate_getLocalTimezone(const picojson::value& /*args*/, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); std::string local_timezone = TimeManager::GetDefaultTimezone(); @@ -160,7 +160,7 @@ void TimeInstance::TZDate_getLocalTimezone(const picojson::value& /*args*/, pico } void TimeInstance::TZDate_GetTimezoneOffset(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); if (!args.contains("timezone") || !args.contains("timestamp")) { LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out, ("Required parameters are missing: \"timezone\", \"timestamp\"")); @@ -188,7 +188,7 @@ void TimeInstance::TZDate_GetTimezoneOffset(const picojson::value& args, picojso void TimeInstance::ToStringTemplate(const picojson::value& args, bool use_locale_fmt, TimeUtilTools::DateTimeFormatType type, picojson::object* out) { - LoggerD("Entered"); + ScopeLogger(); if (!args.contains("timezone") || !args.contains("timestamp")) { LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), out, ("Required parameters are missing: \"timezone\", \"timestamp\"")); @@ -217,38 +217,38 @@ void TimeInstance::ToStringTemplate(const picojson::value& args, bool use_locale } void TimeInstance::TZDate_toLocaleDateString(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); ToStringTemplate(args, true, TimeUtilTools::DateTimeFormatType::kDateFormat, &out); } void TimeInstance::TZDate_toLocaleTimeString(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); ToStringTemplate(args, true, TimeUtilTools::DateTimeFormatType::kTimeFormat, &out); } void TimeInstance::TZDate_toLocaleString(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); ToStringTemplate(args, true, TimeUtilTools::DateTimeFormatType::kDateTimeFormat, &out); } void TimeInstance::TZDate_toDateString(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); ToStringTemplate(args, false, TimeUtilTools::DateTimeFormatType::kDateFormat, &out); } void TimeInstance::TZDate_toTimeString(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); ToStringTemplate(args, false, TimeUtilTools::DateTimeFormatType::kTimeFormat, &out); } void TimeInstance::TZDate_toString(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); ToStringTemplate(args, false, TimeUtilTools::DateTimeFormatType::kDateTimeFormat, &out); } void TimeInstance::TZDate_getTimezoneAbbreviation(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); LoggerW( "DEPRECATION WARNING: getTimezoneAbbreviation() is deprecated and will be removed from next " "release."); @@ -279,7 +279,7 @@ void TimeInstance::TZDate_getTimezoneAbbreviation(const picojson::value& args, } void TimeInstance::TZDate_isDST(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); if (!args.contains("timezone") || !args.contains("timestamp")) { LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out, ("Required parameters are missing: \"timezone\", \"timestamp\"")); @@ -305,7 +305,7 @@ void TimeInstance::TZDate_isDST(const picojson::value& args, picojson::object& o void TimeInstance::TZDate_getPreviousDSTTransition(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); if (!args.contains("timezone") || !args.contains("timestamp")) { LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out, ("Required parameters are missing: \"timezone\", \"timestamp\"")); @@ -327,7 +327,7 @@ void TimeInstance::TZDate_getPreviousDSTTransition(const picojson::value& args, } void TimeInstance::TZDate_getNextDSTTransition(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); if (!args.contains("timezone") || !args.contains("timestamp")) { LogAndReportError(PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid parameter passed."), &out, ("Required parameters are missing: \"timezone\", \"timestamp\"")); diff --git a/src/time/time_manager.cc b/src/time/time_manager.cc index 1c38da6..1d32c23 100644 --- a/src/time/time_manager.cc +++ b/src/time/time_manager.cc @@ -35,11 +35,11 @@ TimeManager::TimeManager(TimeInstance* instance) current_timezone_(GetDefaultTimezone()), is_time_listener_registered_(false), is_timezone_listener_registered_(false) { - LoggerD("Entered"); + ScopeLogger(); } TimeManager::~TimeManager() { - LoggerD("Entered"); + ScopeLogger(); if (is_time_listener_registered_) { UnregisterVconfCallback(kTimeChange); } @@ -51,7 +51,7 @@ TimeManager::~TimeManager() { PlatformResult TimeManager::GetTimezoneOffset(const std::string& timezone_id, const std::string& timestamp_str, std::string* offset, std::string* modifier) { - LoggerD("Entered"); + ScopeLogger(); std::unique_ptr unicode_id(new UnicodeString(timezone_id.c_str())); std::unique_ptr tz(TimeZone::createTimeZone(*unicode_id)); @@ -91,7 +91,7 @@ PlatformResult TimeManager::GetTimezoneOffset(const std::string& timezone_id, } PlatformResult TimeManager::RegisterVconfCallback(ListenerType type) { - LoggerD("Entered"); + ScopeLogger(); if (!is_time_listener_registered_ && !is_timezone_listener_registered_) { LoggerD("registering listener on platform"); if (0 != vconf_notify_key_changed(VCONFKEY_SYSTEM_TIME_CHANGED, OnTimeChangedCallback, this)) { @@ -116,7 +116,7 @@ PlatformResult TimeManager::RegisterVconfCallback(ListenerType type) { } PlatformResult TimeManager::UnregisterVconfCallback(ListenerType type) { - LoggerD("Entered"); + ScopeLogger(); switch (type) { case kTimeChange: is_time_listener_registered_ = false; @@ -141,7 +141,7 @@ PlatformResult TimeManager::UnregisterVconfCallback(ListenerType type) { } void TimeManager::OnTimeChangedCallback(keynode_t* /*node*/, void* event_ptr) { - LoggerD("Entered"); + ScopeLogger(); TimeManager* manager = static_cast(event_ptr); TimeInstance* instance = manager->GetTimeInstance(); std::string defaultTimezone = GetDefaultTimezone(); @@ -165,7 +165,7 @@ void TimeManager::OnTimeChangedCallback(keynode_t* /*node*/, void* event_ptr) { } std::string TimeManager::GetDefaultTimezone() { - LoggerD("Entered"); + ScopeLogger(); std::unique_ptr tz(TimeZone::createDefault()); @@ -186,17 +186,14 @@ std::string TimeManager::GetDefaultTimezone() { } std::string TimeManager::GetCurrentTimezone() { - LoggerD("Entered"); return current_timezone_; } void TimeManager::SetCurrentTimezone(const std::string& new_timezone) { - LoggerD("Entered"); current_timezone_ = new_timezone; } TimeInstance* TimeManager::GetTimeInstance() { - LoggerD("Entered"); return instance_; } diff --git a/src/time/time_utils.cc b/src/time/time_utils.cc index 3f1d446..b8e35a3 100644 --- a/src/time/time_utils.cc +++ b/src/time/time_utils.cc @@ -34,7 +34,7 @@ namespace time { UDate TimeUtilTools::GetDSTTransition(UDate timestamp, const std::shared_ptr& timezone_id, DSTTransition tr_type) { - LoggerD("Entered"); + ScopeLogger(); UBool result = false; UDate dst_transition_date = timestamp; std::unique_ptr vtz(VTimeZone::createVTimeZoneByID(*timezone_id)); @@ -61,7 +61,7 @@ UDate TimeUtilTools::GetDSTTransition(UDate timestamp, PlatformResult TimeUtilTools::IsDST(UDate timestamp, const std::shared_ptr& timezone_id, bool* result_bool) { - LoggerD("Entered"); + ScopeLogger(); UErrorCode ec = U_ZERO_ERROR; std::unique_ptr tz(TimeZone::createTimeZone(*timezone_id)); std::unique_ptr calendar(Calendar::createInstance(*tz, ec)); @@ -86,7 +86,7 @@ PlatformResult TimeUtilTools::IsDST(UDate timestamp, PlatformResult TimeUtilTools::GetTimezoneAbbreviation( UDate date, const std::shared_ptr& timezone_id, std::string* result_string) { - LoggerD("Entered"); + ScopeLogger(); UErrorCode ec = U_ZERO_ERROR; UnicodeString str; @@ -117,7 +117,7 @@ PlatformResult TimeUtilTools::ToStringHelper(UDate date, bool use_locale_fmt, TimeUtilTools::DateTimeFormatType type, std::string* result_string) { - LoggerD("Entered"); + ScopeLogger(); UErrorCode ec = U_ZERO_ERROR; UnicodeString str; @@ -142,7 +142,7 @@ PlatformResult TimeUtilTools::ToStringHelper(UDate date, PlatformResult TimeUtilTools::ToUTF8String(const UnicodeString& uni_str, std::string* result_string) { - LoggerD("Entered"); + ScopeLogger(); int buffer_len = sizeof(UChar) * static_cast(uni_str.length()) + 1; std::unique_ptr result_buffer(static_cast(malloc(buffer_len)), @@ -165,12 +165,12 @@ PlatformResult TimeUtilTools::ToUTF8String(const UnicodeString& uni_str, } UnicodeString* TimeUtilTools::ToUnicodeString(const std::string& str) { - LoggerD("Entered"); + ScopeLogger(); return new UnicodeString(str.c_str()); } PlatformResult TimeUtilTools::GetLocalTimeZone(std::string* result_string) { - LoggerD("Entered"); + ScopeLogger(); UnicodeString id; std::unique_ptr zone(TimeZone::createDefault()); zone->getID(id); @@ -184,7 +184,7 @@ PlatformResult TimeUtilTools::GetLocalTimeZone(std::string* result_string) { } Locale* TimeUtilTools::GetDefaultLocale() { - LoggerD("Entered"); + ScopeLogger(); char* tempstr = vconf_get_str(VCONFKEY_REGIONFORMAT); if (nullptr == tempstr) { @@ -213,7 +213,7 @@ Locale* TimeUtilTools::GetDefaultLocale() { } UnicodeString TimeUtilTools::GetDateTimeFormat(DateTimeFormatType type, bool use_locale_fmt) { - LoggerD("Entered"); + ScopeLogger(); UErrorCode ec = U_ZERO_ERROR; Locale* default_locale = GetDefaultLocale(); @@ -270,7 +270,7 @@ UnicodeString TimeUtilTools::GetDateTimeFormat(DateTimeFormatType type, bool use } PlatformResult TimeUtilTools::GetDateFormat(bool shortformat, std::string* result_string) { - LoggerD("Entered"); + ScopeLogger(); UnicodeString time_format = TimeUtilTools::GetDateTimeFormat( (shortformat ? DateTimeFormatType::kDateShortFormat : DateTimeFormatType::kDateFormat), true); time_format = time_format.findAndReplace("E", "D"); @@ -303,7 +303,7 @@ PlatformResult TimeUtilTools::GetDateFormat(bool shortformat, std::string* resul } PlatformResult TimeUtilTools::GetTimeFormat(std::string* result_string) { - LoggerD("Entered"); + ScopeLogger(); UnicodeString time_format = TimeUtilTools::GetDateTimeFormat(DateTimeFormatType::kTimeFormat, true); time_format = time_format.findAndReplace("H", "h"); @@ -328,7 +328,7 @@ PlatformResult TimeUtilTools::GetTimeFormat(std::string* result_string) { } PlatformResult TimeUtilTools::GetAvailableTimezones(picojson::array* available_timezones) { - LoggerD("Entered"); + ScopeLogger(); UErrorCode ec = U_ZERO_ERROR; std::unique_ptr tz_enum(TimeZone::createEnumeration()); const char* str = nullptr; diff --git a/src/tvinputdevice/tvinputdevice_instance.cc b/src/tvinputdevice/tvinputdevice_instance.cc index 068a9de..3983ef9 100644 --- a/src/tvinputdevice/tvinputdevice_instance.cc +++ b/src/tvinputdevice/tvinputdevice_instance.cc @@ -21,11 +21,11 @@ namespace extension { namespace tvinputdevice { TVInputDeviceInstance::TVInputDeviceInstance() { - LoggerD("Enter"); + ScopeLogger(); } TVInputDeviceInstance::~TVInputDeviceInstance() { - LoggerD("Enter"); + ScopeLogger(); } } // namespace tvinputdevice diff --git a/src/utils/utils_extension.cc b/src/utils/utils_extension.cc index 7840e5a..0b9d7a6 100644 --- a/src/utils/utils_extension.cc +++ b/src/utils/utils_extension.cc @@ -11,21 +11,21 @@ extern const char kSource_utils_api[]; common::Extension* CreateExtension() { - LoggerD("Entered"); + ScopeLogger(); return new UtilsExtension; } UtilsExtension::UtilsExtension() { - LoggerD("Entered"); + ScopeLogger(); SetExtensionName("xwalk"); SetJavaScriptAPI(kSource_utils_api); } UtilsExtension::~UtilsExtension() { - LoggerD("Entered"); + ScopeLogger(); } common::Instance* UtilsExtension::CreateInstance() { - LoggerD("Entered"); + ScopeLogger(); return new extension::utils::UtilsInstance(); } diff --git a/src/utils/utils_instance.cc b/src/utils/utils_instance.cc index 5f0eaee..65f5995 100644 --- a/src/utils/utils_instance.cc +++ b/src/utils/utils_instance.cc @@ -23,7 +23,7 @@ UtilsInstance::UtilsInstance() { using std::placeholders::_1; using std::placeholders::_2; - LoggerD("Entered"); + ScopeLogger(); #define REGISTER_SYNC(c, x) RegisterSyncHandler(c, std::bind(&UtilsInstance::x, this, _1, _2)); #define REGISTER_ASYNC(c, x) RegisterSyncHandler(c, std::bind(&UtilsInstance::x, this, _1, _2)); @@ -39,7 +39,7 @@ UtilsInstance::UtilsInstance() { } void UtilsInstance::GetPkgApiVersion(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); std::string api_version; PlatformResult ret = common::tools::GetPkgApiVersion(&api_version); @@ -50,7 +50,7 @@ void UtilsInstance::GetPkgApiVersion(const picojson::value& args, picojson::obje } void UtilsInstance::CheckPrivilegeAccess(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const auto& privilege = args.get("privilege").to_str(); CHECK_PRIVILEGE_ACCESS(privilege, &out); ReportSuccess(out); @@ -58,7 +58,7 @@ void UtilsInstance::CheckPrivilegeAccess(const picojson::value& args, picojson:: void UtilsInstance::CheckBackwardCompabilityPrivilegeAccess(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const auto& current_priv = args.get("current_privilege").to_str(); const auto& prev_priv = args.get("previous_privilege").to_str(); @@ -79,7 +79,7 @@ const double kTwoPow64 = 18446744073709551616.0; } // namespace void UtilsInstance::ToLongLong(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const auto& n = args.get("n"); long long output = 0; @@ -98,7 +98,7 @@ void UtilsInstance::ToLongLong(const picojson::value& args, picojson::object& ou } void UtilsInstance::ToUnsignedLongLong(const picojson::value& args, picojson::object& out) { - LoggerD("Entered"); + ScopeLogger(); const auto& n = args.get("n"); unsigned long long output = 0; diff --git a/src/websetting/websetting_extension.cc b/src/websetting/websetting_extension.cc index c84f7a0..beaf01e 100644 --- a/src/websetting/websetting_extension.cc +++ b/src/websetting/websetting_extension.cc @@ -24,16 +24,16 @@ common::Extension* CreateExtension() { } WebSettingExtension::WebSettingExtension() { - LoggerD("Entered"); + ScopeLogger(); SetExtensionName("tizen.websetting"); SetJavaScriptAPI(kSource_websetting_api); } WebSettingExtension::~WebSettingExtension() { - LoggerD("Entered"); + ScopeLogger(); } common::Instance* WebSettingExtension::CreateInstance() { - LoggerD("Entered"); + ScopeLogger(); return new common::ParsedInstance(); } diff --git a/src/widgetservice/widgetservice_instance.cc b/src/widgetservice/widgetservice_instance.cc index eb1232d..5154554 100644 --- a/src/widgetservice/widgetservice_instance.cc +++ b/src/widgetservice/widgetservice_instance.cc @@ -150,7 +150,7 @@ int WidgetLifecycleCb(const char* widget_id, widget_lifecycle_event_e lifecycle_ } void bundleIterator(const char* key, const char* val, void* data) { - LOGD("Entered, adding key-pair value: (%s) - (%s)", key, val); + ScopeLogger("adding key-pair value: %s; val: %s", key, val); auto obj = static_cast(data); obj->insert(std::make_pair(key, picojson::value(val))); } @@ -232,6 +232,7 @@ TizenResult WidgetServiceInstance::GetWidgets(const picojson::object& args, } auto get_widgets = [this, pkgid](const common::AsyncToken& token) -> void { + ScopeLogger("Entered into asynchronous function, get_widget"); int ret = WIDGET_ERROR_NONE; picojson::value response{picojson::array{}}; auto* array = &response.get(); @@ -342,6 +343,7 @@ TizenResult WidgetServiceInstance::GetInstances(picojson::object const& args, const auto& widget_id = args.find(kWidgetId)->second.get(); auto get_instances = [this, widget_id](const common::AsyncToken& token) -> void { + ScopeLogger("Entered into asynchronous function, get_instances"); picojson::value response{picojson::array{}}; auto* array = &response.get(); @@ -408,6 +410,7 @@ TizenResult WidgetServiceInstance::GetVariants(picojson::object const& args, const auto& widget_id = args.find(kWidgetId)->second.get(); auto get_variants = [this, widget_id](const common::AsyncToken& token) -> void { + ScopeLogger("Entered into asynchronous function, get_variants"); int count = 0; int* type_array = nullptr; int ret = widget_service_get_supported_size_types(widget_id.c_str(), &count, &type_array); @@ -603,6 +606,7 @@ TizenResult WidgetServiceInstance::GetContent(picojson::object const& args, const auto& instance_id = args.find(kInstanceId)->second.get(); auto get_content = [this, widget_id, instance_id](const common::AsyncToken& token) -> void { + ScopeLogger("Entered into asynchronous function, get_content"); bundle* bundle_data = bundle_create(); int ret = get_last_result(); -- 2.7.4 From 95cbb2af09252e7b817a9358616b6362f5e863af Mon Sep 17 00:00:00 2001 From: Pawel Kaczmarczyk Date: Tue, 31 Oct 2017 13:53:47 +0100 Subject: [PATCH 04/16] [Callhistory] Fix for find method [Bug] LoadPhoneNumbers must be called before FindThread. Because of critical section of LoadPhoneNumbers lasts for whole scope, so they can be called sequentially. [Verification] Passrate 100% Change-Id: I8207f488f0f4926d70d2289d42b1a46d2b98ee75 Signed-off-by: Pawel Kaczmarczyk --- src/callhistory/callhistory.cc | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/callhistory/callhistory.cc b/src/callhistory/callhistory.cc index f531118..1108c80 100644 --- a/src/callhistory/callhistory.cc +++ b/src/callhistory/callhistory.cc @@ -305,8 +305,11 @@ void CallHistory::LoadPhoneNumbers(const picojson::object& args, CallHistory* ca void CallHistory::find(const picojson::object& args) { ScopeLogger(); - std::thread(LoadPhoneNumbers, args, this).detach(); - std::thread(FindThread, args, this).detach(); + std::thread([args, this]() { + ScopeLogger("Entered into asynchronus function, std::thread's argument"); + LoadPhoneNumbers(args, this); + FindThread(args, this); + }).detach(); } PlatformResult CallHistory::remove(const picojson::object& args) { -- 2.7.4 From caae5b05a5921a532ae7f3b2e2eab507b9005bb9 Mon Sep 17 00:00:00 2001 From: Rafal Walczyna Date: Thu, 2 Nov 2017 15:08:00 +0100 Subject: [PATCH 05/16] [Content] Crash in CreateThumbnail fixed [verification] 100% passrate on TM1 target and emulator Change-Id: Ia2f8fe4ab6996ba872573235cfccc600282cc8f0 Signed-off-by: Rafal Walczyna --- src/content/content_manager.cc | 29 +++++++++++++---------------- src/content/content_manager.h | 8 ++++++++ 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/content/content_manager.cc b/src/content/content_manager.cc index c12e3db..ab88887 100644 --- a/src/content/content_manager.cc +++ b/src/content/content_manager.cc @@ -647,22 +647,22 @@ static bool playlist_content_member_cb(int playlist_member_id, media_info_h medi void CreateThumbnailCallback(media_content_error_e err, const char* path, void* user_data) { ScopeLogger(); - unsigned int* callbackId = (unsigned int*)user_data; - if (nullptr == callbackId) { - LoggerD("Callback id is null"); + std::unique_ptr callback_data_ptr( + (CreateThumbnailCallbackData*)user_data); + if (0 == callback_data_ptr->callback_id) { + LoggerD("Callback id is 0"); return; } if (!(ContentManager::getInstance()->getContentInstance())) { // There is not instance already LoggerD("There is not instance now"); - delete callbackId; return; } picojson::object out; - out["callbackId"] = picojson::value(static_cast(*callbackId)); + out["callbackId"] = picojson::value(callback_data_ptr->callback_id); if (MEDIA_CONTENT_ERROR_NONE == err) { out["result"] = picojson::value(std::string(path)); @@ -672,7 +672,6 @@ void CreateThumbnailCallback(media_content_error_e err, const char* path, void* LogAndReportError(result, &out, ("Failed to create a thumbnail")); } - delete callbackId; common::Instance::PostMessage(ContentManager::getInstance()->getContentInstance(), picojson::value(out).serialize().c_str()); } @@ -1603,26 +1602,24 @@ int ContentManager::getNumberOfTracks(int id, int* result) { common::PlatformResult ContentManager::createThumbnail(const picojson::value& args) { ScopeLogger(); - unsigned int* callbackId = - new unsigned int(static_cast(args.get("callbackId").get())); + std::unique_ptr callback_data_ptr{new CreateThumbnailCallbackData}; + callback_data_ptr->callback_id = args.get("callbackId").get(); std::string id = args.get("id").get(); - media_info_h media = NULL; - int ret = media_info_get_media_from_db(id.c_str(), &media); - if (MEDIA_CONTENT_ERROR_NONE != ret && nullptr == media) { - delete callbackId; + int ret = media_info_get_media_from_db(id.c_str(), &callback_data_ptr->media); + if (MEDIA_CONTENT_ERROR_NONE != ret && nullptr == callback_data_ptr->media) { return LogAndCreateResult(ErrorCode::ABORT_ERR, "Getting media is failed.", ("Getting media is failed: %d (%s)", ret, get_error_message(ret))); } - ret = media_info_create_thumbnail(media, CreateThumbnailCallback, (void*)callbackId); - media_info_destroy(media); + ret = media_info_create_thumbnail(callback_data_ptr->media, CreateThumbnailCallback, + static_cast(callback_data_ptr.get())); + if (MEDIA_CONTENT_ERROR_NONE != ret) { - delete callbackId; return LogAndCreateResult(ErrorCode::ABORT_ERR, "Creating thumbnail failed.", ("Creating thumbnail failed: %d (%s)", ret, get_error_message(ret))); } - + callback_data_ptr.release(); return PlatformResult(ErrorCode::NO_ERROR); } diff --git a/src/content/content_manager.h b/src/content/content_manager.h index d09adff..1801ec4 100644 --- a/src/content/content_manager.h +++ b/src/content/content_manager.h @@ -38,6 +38,14 @@ typedef std::unique_ptr::type, void (*)(me void ContentToJson(media_info_h info, picojson::object& o); void ContentDirToJson(media_folder_h folder, picojson::object& o); +struct CreateThumbnailCallbackData { + double callback_id; + media_info_h media; + ~CreateThumbnailCallbackData() { + media_info_destroy(media); + } +}; + class ContentManager { public: virtual ~ContentManager(); -- 2.7.4 From 73ee39927b7c57c439e57a8a5c068454a291505d Mon Sep 17 00:00:00 2001 From: Michal Bistyga Date: Thu, 2 Nov 2017 14:59:11 +0100 Subject: [PATCH 06/16] [Logger] Removing warning from code analysis [Verification] Code compiles, random packages pass their tests Change-Id: Ibfa0053c23faa5b4b6a1e49da633289719af1bd7 Signed-off-by: Michal Bistyga --- src/common/logger.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/logger.h b/src/common/logger.h index 66036ac..fd159bb 100644 --- a/src/common/logger.h +++ b/src/common/logger.h @@ -237,7 +237,7 @@ class ScopeLogger { } template - ScopeLogger(const std::string& f, const std::string& m, int l, const std::string& ex = "", + ScopeLogger(const std::string& f, const std::string& m, int l, const std::string& ex, Args... args) : file_(f), method_(m), extra_(ex) { #ifdef TIZEN_DEBUG_ENABLE -- 2.7.4 From e8d6fa4b5ee1757193f100fc314a66eaab8d472a Mon Sep 17 00:00:00 2001 From: Piotr Kosko Date: Mon, 6 Nov 2017 10:01:24 +0100 Subject: [PATCH 07/16] [version] 2.06 Change-Id: I6076c3c5b8269e4c27b7cdcb1f4437f36e5821a5 Signed-off-by: Piotr Kosko --- packaging/webapi-plugins.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/webapi-plugins.spec b/packaging/webapi-plugins.spec index d5e9892..1a86313 100644 --- a/packaging/webapi-plugins.spec +++ b/packaging/webapi-plugins.spec @@ -10,7 +10,7 @@ %define crosswalk_extensions_path %{_libdir}/%{crosswalk_extensions} Name: webapi-plugins -Version: 2.05 +Version: 2.06 Release: 0 License: Apache-2.0 and BSD-3-Clause and MIT Group: Development/Libraries -- 2.7.4 From 05ea11618721d6d8bb4e188f435a7dca84788557 Mon Sep 17 00:00:00 2001 From: Lukasz Bardeli Date: Tue, 7 Nov 2017 08:14:13 +0100 Subject: [PATCH 08/16] [Exif] remove unnecessary semicolon Change-Id: If8ad91e6faf4be242067278b611d260b5d967e84 Signed-off-by: Lukasz Bardeli --- src/exif/exif_information.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/src/exif/exif_information.cc b/src/exif/exif_information.cc index 08f7ed9..e975ea2 100644 --- a/src/exif/exif_information.cc +++ b/src/exif/exif_information.cc @@ -228,7 +228,6 @@ void ExifInformation::setExposureTime(const Rational& exposure_time) { const std::string& ExifInformation::getExposureProgramString() { LoggerD("Entered"); return ExifUtil::exposureProgramToString(m_exposure_program); - ; } ExposureProgram ExifInformation::getExposureProgram() { -- 2.7.4 From 1c5009f1afb3f1ae04a1ae85e29db89e6a520f52 Mon Sep 17 00:00:00 2001 From: Jakub Skowron Date: Mon, 6 Nov 2017 14:36:22 +0100 Subject: [PATCH 09/16] [Documentation] Remove unnecessary file logo.png This is a logo for documentation generator. Not used in documentation Change-Id: I508793c952bd35ede3ec95b31e6876f942f2dab5 --- doc/html/images/logo.png | Bin 3369 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 doc/html/images/logo.png diff --git a/doc/html/images/logo.png b/doc/html/images/logo.png deleted file mode 100644 index a913f5df6b5976acdd7f8c6a904c041b1ccf745c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3369 zcmaJ^dpy(YAD?TbxrSV#HTT%qW^0xutRW^LxrNz=VHexni(C@9g(wFlDY>L0$Gzw% zCUo4A4oT#a;s}Wy;y0bsIln)C{l2g7_xn80=kMw07Ni(9lq5C<4l0`Rc=rjEuH9;BW}v1HulcbBJLOI$P~K1CGKb zv8YTAl|ct>GZMWS!5l1@pXpyE(3tANF=@c&(Dw12$W z9DB;Y`TkF0wqrPxqHj-OGlE$p{@{GnwnH&7<}3=4!(cfw7=horXy?b^FxY+!Cdk|Y z1=1!ENmTl_LFXHSK)_hh*&HIBM6tqQ!F&!Vl}g5-aA+JFZh$bw8ydl2$KYmo82p&I z8QK&LN8k?O;NP)01}T_Ep>w`t$^T*ve~8@{1C7a#jH9rqArvy6#h`({6^)_(I2YIt z`ToX|f1C^ahgf}nGWy%2{jX7fH}Unez5PeH{KG%er_lL&XYqwy5G4o(0CweB;Y=OF zhUeUN2g(k~VG-5U(a|rXh1w}u!;sc`X}V6Yyctm3QN2pWZsZqxoU4PZ-37n6+jwpN z7YW6w!^e-FzY~9#a3NMuM&0pvz9d@2+r~Ra#eWVtSF#!T=;N8l7R121PpBNXVypf3 zpvT7#_k7<(E>El6i0o<7WnU@+QMMx6OKL$P?w!-U^|L_CDv&uXl&CvIG$l&sm?gXo z-TZ(bz&#^OfHxk{b*4^JisZ&lLNOyC#SPpNov zEf33ha`S)kd7vU`e6y`EZ|_yw+pBl>ia0UcE+Qi!o#9q6>nDk>@I|VFTGa7EBhRta z@HQvCp66|%S*qm)AsaW>tkG8{p6wG_U2>8hNl$1<7?AvLBi4l*DeW<6_nd+j1-YgJzv(OQ3 zost@`CPGohpKn2Kbe5dB!Q*wx>E`c+df3cwxF_x*O`j!CLb^{)8a^s-sH@yKe7Am6 zV)OGWiL>>A5Zh_UWa#G|gbQ1DJ>$n(YQ>_DtOGu{=1lmc3sk0g0P9CzW1Rv9|6KX# zG5g^|yaT_KNJEWpcIDa z?hR#rR(%O`yz4bomwOuLDievlBk9vU=={SB{IWR0_({a4hY3fe3lGd{`@iy)F3NdK zsvMF|jF7|K>e~r9!*0wMzpAWMJ3Tq+zFyxP1s+66Gqon7+j6Wv?+3N`iha$cv?-!p z-d5U>uz4kGZ`|+~k7uCPyGGJ|j!<{M-)d$CZI)(EjlF4`?eFY)q^102|7X&SK74U5 zIXrANR&i8lA2?$txKGOLCP**_kZ|$h_v6;9~rqp!-$=%uS7Zxl|oRF+J*U{Zk zQP|s1x4A@lr!F53R#o)p)_dlXv;4UVq+IWB~O3C5V`XS^xIDNNl|$gG;!YauhAJ&-6K43~hTSXl`G- zs|36!E=%3=#S+jaM!|A!cSdziRXWTzv*>Au)YnS4GtSP=_~f-Pnds~!sf=ztQhZib zdpCY-F|c-;v43UL(=mI@wLzwi{(JPbysSqivcRMiMSx2C$DbT`=b);EaUKMAhHpm}nbi{Zg+_u?df5Uf5|Xr2sYL3i}4r`i5R9XyW_(`ycns zNC}|cue7UnC|DZVX@=liGh_u3M%*NC8#@EdPlESj+go+liOMS38gjspGhoeB;p2(| znxvdIZ_|hfOp$O((lp`FdnT{iR*n-4Rnos~omq?nkNb(mDgwAD$FB3YaxUP~(y8*I z;yp);joah#rltbqVUGNgg54G6QwEB5;XGd1+-d}ti9WODx@bI?x3`s0Ekd02P|_Or zFDHoKlIgl2?0)5D-h*5NTV21|*S7^Nx@E#7{tyrd*)gh#Y|YxC6Cc6}dED4h_JzdL z)jG77C#OEWRa6VXprywM<amV&Kr#Mlbu>+?ZMB^^K00dq0WGiLSXjM+A~dU|C*s)2mCKU9{dq zHRlWVM%MN^h;b(Q4xfyxeRUfg$Zyq0Ld_@sM4N;eU?CUh*L6N?cn8Z zWKn!Tox5M*vP)F0$o_-Ji%V^AzSulBqa{Qks(^#WUI@;H=yJtwqnM z_5Ou7YU7JnY|A5K3%hvvL9pP`=@v_8Y_-ML7fN%Wq=Lp1}Tu|aBtv{SfZJMFcM=#H^#bd-sY zp+e|MkArIMK`G&41q0XShB6h18t@xqCBU%8;R4&Ca*2|6_f_u?{i<2o6h=h7yr$in zwxV+80k|SKA6DHLU3{vYThrqe)s+%s?VJcWu&l40A6>C>XZ~DPU;UXEiEg_ZjK4fm z)}_Hx)Js4+)0(bIPxysr+1-TEFrc;+b`igx_9LD>xWyfdCST@LxW$-N}8I2 z6ACpvCZ5W2fi^dXPwrXpM6_-0YJ%?)we`h@zI+9Xk+Xm!5c_p>bX3AB3%zwHYFsRn9m%JLJTQ_oKsq%9yznhHD{i#e!89_W>anzb+ho#JL wo6W4hE Date: Tue, 7 Nov 2017 18:28:52 +0100 Subject: [PATCH 10/16] [Documentation] Add license information for tools in doc Some parts of automatically generated documentation was missing license information. Change-Id: I1df6f3145050800d5fbd6babcc5234bd76128d6b --- doc/html/js/COPYING.prettify | 191 +++++++++++++++++++++++++++++++++++++++++++ doc/html/js/LICENSE | 11 +++ 2 files changed, 202 insertions(+) create mode 100644 doc/html/js/COPYING.prettify create mode 100644 doc/html/js/LICENSE diff --git a/doc/html/js/COPYING.prettify b/doc/html/js/COPYING.prettify new file mode 100644 index 0000000..b7f86df --- /dev/null +++ b/doc/html/js/COPYING.prettify @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2011 Mike Samuel et al + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/doc/html/js/LICENSE b/doc/html/js/LICENSE new file mode 100644 index 0000000..0b2856a --- /dev/null +++ b/doc/html/js/LICENSE @@ -0,0 +1,11 @@ +Licensing of files in this directory: + +blank.html - MIT License (https://www.npmjs.org/package/doctor-md), author: Dimitar Christoff (https://twitter.com/D_mitar) +doctor.js - MIT License (https://www.npmjs.org/package/doctor-md), author: Dimitar Christoff (https://twitter.com/D_mitar) +moostrap-scrollspy.js - MIT License (http://github.com/DimitarChristoff/mootstrap-scrollspy/), author: Dimitar Christoff (https://twitter.com/D_mitar) +mootools-yui-compressed.js - MIT License (http://mootools.net/), Copyright 2006-2017 Valerio Proietti & MooTools Developers +prettify.js - Apache License 2.0 (https://github.com/google/code-prettify), Copyright 2011 Mike Samuel et al +lang-css.js - Apache License 2.0 (https://github.com/google/code-prettify), Copyright 2011 Mike Samuel et al + +Full text of Apache License 2.0 is in file COPYING.prettify +Full text of MIT License is in root direcotry of this project (LICENSE.MIT) -- 2.7.4 From cd72bb0b4cd8e8bb4155127bf9ab31945ba64fcd Mon Sep 17 00:00:00 2001 From: Piotr Kosko Date: Wed, 8 Nov 2017 08:20:25 +0100 Subject: [PATCH 11/16] [version] 2.07 Change-Id: Ia8d9706056bab38aabd9d5cda41980b8bd527b33 Signed-off-by: Piotr Kosko --- packaging/webapi-plugins.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/webapi-plugins.spec b/packaging/webapi-plugins.spec index 1a86313..b1112ed 100644 --- a/packaging/webapi-plugins.spec +++ b/packaging/webapi-plugins.spec @@ -10,7 +10,7 @@ %define crosswalk_extensions_path %{_libdir}/%{crosswalk_extensions} Name: webapi-plugins -Version: 2.06 +Version: 2.07 Release: 0 License: Apache-2.0 and BSD-3-Clause and MIT Group: Development/Libraries -- 2.7.4 From 7f55c4e6b1f8562e431fc3079c2c47bc95003532 Mon Sep 17 00:00:00 2001 From: Rafal Walczyna Date: Mon, 23 Oct 2017 15:19:47 +0200 Subject: [PATCH 12/16] [humanactivitymonitor] Fix generating query for recording [Verification] 100% passrate on TW1 Before fix function readRecorderData() returned only one value, now it returns multiple values - as expected Change-Id: I2d0de2633e2e7fd55aa6f04aadad4a0fb3569d4a Signed-off-by: Rafal Walczyna --- src/humanactivitymonitor/humanactivitymonitor_manager.cc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/humanactivitymonitor/humanactivitymonitor_manager.cc b/src/humanactivitymonitor/humanactivitymonitor_manager.cc index 269f308..4b08cd0 100644 --- a/src/humanactivitymonitor/humanactivitymonitor_manager.cc +++ b/src/humanactivitymonitor/humanactivitymonitor_manager.cc @@ -849,7 +849,12 @@ class HumanActivityMonitorManager::Monitor::SensorMonitor if (query.get(it.second).is()) { val = query.get(it.second).get(); if (0 <= val) { - int ret = sensor_recorder_query_set_time(query_h, it.first, val); + int ret; + if (SENSOR_RECORDER_QUERY_TIME_INTERVAL != it.first) { + ret = sensor_recorder_query_set_time(*query_h, it.first, val); + } else { + ret = sensor_recorder_query_set_int(*query_h, it.first, val); + } if (SENSOR_ERROR_NONE != ret) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to set query parameter", ("Failed to set (%d) query parameter, error: %d (%s)", -- 2.7.4 From 146ddcf3c31e36847c68568a661cb8f0a176f4ce Mon Sep 17 00:00:00 2001 From: Piotr Kosko Date: Fri, 17 Nov 2017 11:14:10 +0100 Subject: [PATCH 13/16] [version] 2.08 Change-Id: Ic0dd5f3b4fb5f004f3b3f7d993bbae2761f84392 Signed-off-by: Piotr Kosko --- packaging/webapi-plugins.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/webapi-plugins.spec b/packaging/webapi-plugins.spec index b1112ed..d085250 100644 --- a/packaging/webapi-plugins.spec +++ b/packaging/webapi-plugins.spec @@ -10,7 +10,7 @@ %define crosswalk_extensions_path %{_libdir}/%{crosswalk_extensions} Name: webapi-plugins -Version: 2.07 +Version: 2.08 Release: 0 License: Apache-2.0 and BSD-3-Clause and MIT Group: Development/Libraries -- 2.7.4 From 4c779851d4dd3a8b3c3ccf9daa95ca592b24621d Mon Sep 17 00:00:00 2001 From: Pawel Kaczmarczyk Date: Mon, 20 Nov 2017 11:39:32 +0100 Subject: [PATCH 14/16] [Messaging] Refactor singleton managers into instance's fields to prevent crash Callback could be called even after MessagingInstance object was destroyed. [Verification] Passrate didn't change Change-Id: I3ac0db270f9f7a07613a9bd53e18f3b954952944 Signed-off-by: Pawel Kaczmarczyk --- src/messaging/DBus/MessageProxy.cpp | 15 +++--- src/messaging/DBus/MessageProxy.h | 6 ++- src/messaging/DBus/SendProxy.cpp | 11 ++-- src/messaging/DBus/SendProxy.h | 6 ++- src/messaging/callback_user_data.cc | 16 +++++- src/messaging/callback_user_data.h | 9 +++- src/messaging/change_listener_container.cc | 2 - src/messaging/conversation_callback_data.cc | 3 +- src/messaging/conversation_callback_data.h | 3 +- src/messaging/conversations_change_callback.cc | 5 +- src/messaging/conversations_change_callback.h | 3 +- src/messaging/email_manager.cc | 45 ++++++++-------- src/messaging/email_manager.h | 10 ++-- src/messaging/find_msg_callback_user_data.cc | 5 +- src/messaging/find_msg_callback_user_data.h | 2 +- src/messaging/folders_change_callback.cc | 4 +- src/messaging/folders_change_callback.h | 3 +- src/messaging/message.cc | 6 ++- src/messaging/message.h | 3 +- src/messaging/message_callback_user_data.cc | 5 +- src/messaging/message_callback_user_data.h | 2 +- src/messaging/message_service.cc | 24 +++++---- src/messaging/message_service.h | 11 ++-- src/messaging/message_service_email.cc | 42 +++++++-------- src/messaging/message_service_email.h | 7 ++- src/messaging/message_service_short_msg.cc | 17 +++--- src/messaging/message_service_short_msg.h | 6 +-- src/messaging/message_storage_email.cc | 15 +++--- src/messaging/message_storage_short_msg.cc | 12 ++--- src/messaging/messages_callback_user_data.cc | 3 +- src/messaging/messages_callback_user_data.h | 3 +- src/messaging/messages_change_callback.cc | 4 +- src/messaging/messages_change_callback.h | 3 +- src/messaging/messaging_extension.cc | 5 +- src/messaging/messaging_instance.cc | 71 +++++++++++++++----------- src/messaging/messaging_instance.h | 6 +++ src/messaging/messaging_manager.cc | 12 +++-- src/messaging/messaging_util.cc | 7 +-- src/messaging/messaging_util.h | 3 +- src/messaging/short_message_manager.cc | 53 +++++++++---------- src/messaging/short_message_manager.h | 15 +++--- 41 files changed, 273 insertions(+), 210 deletions(-) mode change 100755 => 100644 src/messaging/callback_user_data.cc mode change 100755 => 100644 src/messaging/callback_user_data.h diff --git a/src/messaging/DBus/MessageProxy.cpp b/src/messaging/DBus/MessageProxy.cpp index 7cc1653..30e17b5 100644 --- a/src/messaging/DBus/MessageProxy.cpp +++ b/src/messaging/DBus/MessageProxy.cpp @@ -31,10 +31,11 @@ namespace DBus { using namespace common; -MessageProxy::MessageProxy() +MessageProxy::MessageProxy(EmailManager& manager) : common::dbus::Proxy(kDBusPathEmailStorageChange, kDBusIfaceEmailStorageChange, kDBusNameSignalEmail, kDBusPathEmailStorageChange, - kDBusIfaceEmailStorageChange) { + kDBusIfaceEmailStorageChange), + email_manager_(manager) { ScopeLogger(); } @@ -42,9 +43,9 @@ MessageProxy::~MessageProxy() { ScopeLogger(); } -PlatformResult MessageProxy::create(MessageProxyPtr* message_proxy) { +PlatformResult MessageProxy::create(EmailManager& manager, MessageProxyPtr* message_proxy) { ScopeLogger(); - message_proxy->reset(new MessageProxy()); + message_proxy->reset(new MessageProxy(manager)); if ((*message_proxy)->isNotProxyGot()) { message_proxy->reset(); return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get proxy"); @@ -129,7 +130,7 @@ PlatformResult MessageProxy::handleEmailEvent(int account_id, int mail_id, int t } } - email_mail_data_t* mail_data = EmailManager::getInstance().loadMessage(mail_id); + email_mail_data_t* mail_data = email_manager_.loadMessage(mail_id); if (mail_data == NULL) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Failed to load email"); } @@ -170,7 +171,7 @@ PlatformResult MessageProxy::handleEmailEvent(int account_id, int mail_id, int t delete eventMsg; delete eventConv; - EmailManager::getInstance().freeMessage(mail_data); + email_manager_.freeMessage(mail_data); } else { LoggerD("Listener not registered just ignore"); } @@ -226,7 +227,7 @@ void MessageProxy::notifyEmailManager(const std::string& idsString, LoggerD("Mail id list is empty."); return; } - EmailManager::getInstance().removeStatusCallback(ids, status); + email_manager_.removeStatusCallback(ids, status); } void MessageProxy::handleThreadRemoveEvent(int account_id, int thread_id) { diff --git a/src/messaging/DBus/MessageProxy.h b/src/messaging/DBus/MessageProxy.h index 6006117..4089fcd 100644 --- a/src/messaging/DBus/MessageProxy.h +++ b/src/messaging/DBus/MessageProxy.h @@ -30,6 +30,7 @@ namespace extension { namespace messaging { +class EmailManager; namespace DBus { class MessageProxy; @@ -38,10 +39,10 @@ typedef std::shared_ptr MessageProxyPtr; class MessageProxy : public common::dbus::Proxy { public: virtual ~MessageProxy(); - static common::PlatformResult create(MessageProxyPtr *message_proxy); + static common::PlatformResult create(EmailManager &manager, MessageProxyPtr *message_proxy); protected: - MessageProxy(); + MessageProxy(EmailManager &manager); virtual void signalCallback(GDBusConnection *connection, const gchar *sender_name, const gchar *object_path, const gchar *interface_name, const gchar *signal_name, GVariant *parameters); @@ -57,6 +58,7 @@ class MessageProxy : public common::dbus::Proxy { void notifyEmailManager(const std::string &idsString, email_noti_on_storage_event status); void handleThreadRemoveEvent(int account_id, int thread_id); common::PlatformResult handleMailboxEvent(int account_id, int mailbox_id, int event); + EmailManager &email_manager_; }; } // namespace DBus diff --git a/src/messaging/DBus/SendProxy.cpp b/src/messaging/DBus/SendProxy.cpp index 0e8dc8e..f2a57ef 100644 --- a/src/messaging/DBus/SendProxy.cpp +++ b/src/messaging/DBus/SendProxy.cpp @@ -29,7 +29,8 @@ namespace DBus { using namespace common; -SendProxy::SendProxy() : EmailSignalProxy(kDBusPathNetworkStatus, kDBusIfaceNetworkStatus) { +SendProxy::SendProxy(EmailManager& manager) + : EmailSignalProxy(kDBusPathNetworkStatus, kDBusIfaceNetworkStatus), email_manager_(manager) { ScopeLogger(); } @@ -37,9 +38,9 @@ SendProxy::~SendProxy() { ScopeLogger(); } -PlatformResult SendProxy::create(SendProxyPtr* send_proxy) { +PlatformResult SendProxy::create(EmailManager& manager, SendProxyPtr* send_proxy) { ScopeLogger(); - send_proxy->reset(new SendProxy()); + send_proxy->reset(new SendProxy(manager)); if ((*send_proxy)->isNotProxyGot()) { send_proxy->reset(); return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Could not get send proxy"); @@ -59,8 +60,8 @@ void SendProxy::handleEmailSignal(const int status, const int account_id, const "received email signal with:\n status: %d\n account_id: %d\n " "source: %s\n mail_id: %d\n error_code: %d", status, account_id, source.c_str(), mail_id, error_code); - EmailManager::getInstance().sendStatusCallback( - mail_id, static_cast(status), error_code); + email_manager_.sendStatusCallback(mail_id, static_cast(status), + error_code); break; default: LoggerD("Unrecognized status %d, ignoring", status); diff --git a/src/messaging/DBus/SendProxy.h b/src/messaging/DBus/SendProxy.h index e9f211b..8e32716 100644 --- a/src/messaging/DBus/SendProxy.h +++ b/src/messaging/DBus/SendProxy.h @@ -23,6 +23,7 @@ namespace extension { namespace messaging { +class EmailManager; namespace DBus { class SendProxy; @@ -31,12 +32,13 @@ typedef std::shared_ptr SendProxyPtr; class SendProxy : public EmailSignalProxy { public: virtual ~SendProxy(); - static common::PlatformResult create(SendProxyPtr* send_proxy); + static common::PlatformResult create(EmailManager& manager, SendProxyPtr* send_proxy); protected: - SendProxy(); + SendProxy(EmailManager& manager); virtual void handleEmailSignal(const int status, const int account_id, const std::string& source, const int op_handle, const int error_code); + EmailManager& email_manager_; }; } // DBus diff --git a/src/messaging/callback_user_data.cc b/src/messaging/callback_user_data.cc old mode 100755 new mode 100644 index dfe796a..e29ba89 --- a/src/messaging/callback_user_data.cc +++ b/src/messaging/callback_user_data.cc @@ -19,18 +19,22 @@ #include "common/logger.h" #include "common/tools.h" +#include "messaging_instance.h" + using common::tools::ReportSuccess; using common::tools::ReportError; namespace extension { namespace messaging { -CallbackUserData::CallbackUserData(PostQueue& queue, long cid, bool keep /* = false */) +CallbackUserData::CallbackUserData(PostQueue& queue, long cid, MessagingInstance& instance, + bool keep /* = false */) : json_(picojson::object()), obj_(json_.get()), cid_(cid), queue_(queue), - result_(common::ErrorCode::NO_ERROR) { + result_(common::ErrorCode::NO_ERROR), + instance_(instance) { ScopeLogger(); if (!keep) { // this is not listener, add callbackId @@ -101,5 +105,13 @@ void CallbackUserData::AddJsonData(const char* key, const picojson::value& value obj_[key] = value; } +EmailManager& CallbackUserData::getEmailManager() { + return instance_.getEmailManager(); +} + +ShortMsgManager& CallbackUserData::getShortMsgManager() { + return instance_.getShortMsgManager(); +} + } // messaging } // extension diff --git a/src/messaging/callback_user_data.h b/src/messaging/callback_user_data.h old mode 100755 new mode 100644 index 6f72c83..a51aea9 --- a/src/messaging/callback_user_data.h +++ b/src/messaging/callback_user_data.h @@ -26,9 +26,12 @@ namespace extension { namespace messaging { +class EmailManager; +class ShortMsgManager; + class CallbackUserData { public: - CallbackUserData(PostQueue& queue, long cid, bool keep = false); + CallbackUserData(PostQueue& queue, long cid, MessagingInstance& instance, bool keep = false); virtual ~CallbackUserData(); bool IsError() const; @@ -42,6 +45,9 @@ class CallbackUserData { void AddAndPost(PostPriority p); bool HasQueue(const PostQueue& q) const; + EmailManager& getEmailManager(); + ShortMsgManager& getShortMsgManager(); + private: void AddJsonData(const char* key, const picojson::value& value); @@ -50,6 +56,7 @@ class CallbackUserData { long cid_; PostQueue& queue_; common::PlatformResult result_; + MessagingInstance& instance_; }; } // messaging diff --git a/src/messaging/change_listener_container.cc b/src/messaging/change_listener_container.cc index e201c8f..b082446 100644 --- a/src/messaging/change_listener_container.cc +++ b/src/messaging/change_listener_container.cc @@ -211,8 +211,6 @@ ChangeListenerContainer::ChangeListeners::ListenerGroup::Get 0) { - instance.m_slot_size = slot_size; + m_slot_size = slot_size; } - PlatformResult ret = DBus::SyncProxy::create( - DBus::kDBusPathNetworkStatus, DBus::kDBusIfaceNetworkStatus, &instance.m_proxy_sync); + PlatformResult ret = DBus::SyncProxy::create(DBus::kDBusPathNetworkStatus, + DBus::kDBusIfaceNetworkStatus, &m_proxy_sync); CHECK_ERROR(ret, "create sync proxy failed"); - if (!instance.m_proxy_sync) { + if (!m_proxy_sync) { LoggerE("Sync proxy is null"); return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Sync proxy is null"); } - instance.m_proxy_sync->signalSubscribe(); + m_proxy_sync->signalSubscribe(); ret = DBus::LoadBodyProxy::create(DBus::kDBusPathNetworkStatus, DBus::kDBusIfaceNetworkStatus, - &instance.m_proxy_load_body); + &m_proxy_load_body); CHECK_ERROR(ret, "create load body proxy failed"); - if (!instance.m_proxy_load_body) { + if (!m_proxy_load_body) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Load body proxy is null"); } - instance.m_proxy_load_body->signalSubscribe(); + m_proxy_load_body->signalSubscribe(); // ret = DBus::LoadAttachmentProxy::create(DBus::Proxy::DBUS_PATH_NETWORK_STATUS, // DBus::Proxy::DBUS_IFACE_NETWORK_STATUS, @@ -141,21 +134,21 @@ PlatformResult EmailManager::InitializeEmailService() { // } // m_proxy_load_attachment->signalSubscribe(); - ret = DBus::MessageProxy::create(&instance.m_proxy_messageStorage); + ret = DBus::MessageProxy::create(*this, &m_proxy_messageStorage); CHECK_ERROR(ret, "create message proxy failed"); - if (!instance.m_proxy_messageStorage) { + if (!m_proxy_messageStorage) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Message proxy is null"); } - instance.m_proxy_messageStorage->signalSubscribe(); + m_proxy_messageStorage->signalSubscribe(); - ret = DBus::SendProxy::create(&instance.m_proxy_send); + ret = DBus::SendProxy::create(*this, &m_proxy_send); CHECK_ERROR(ret, "create send proxy failed"); - if (!instance.m_proxy_send) { + if (!m_proxy_send) { return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Send proxy is null"); } - instance.m_proxy_send->signalSubscribe(); + m_proxy_send->signalSubscribe(); - instance.m_is_initialized = true; + m_is_initialized = true; } return PlatformResult(ErrorCode::NO_ERROR); @@ -1123,6 +1116,10 @@ PlatformResult EmailManager::FindConversationsPlatform(ConversationCallbackData* std::shared_ptr conversation; PlatformResult ret = MessageConversation::convertEmailConversationToObject( conversationsInfo.at(i).id, &conversation); + if (ret.IsError()) { + LoggerE("%d (%s)", ret.error_code(), (ret.message()).c_str()); + return ret; + } conversation->setUnreadMessages(conversationsInfo.at(i).unreadMessages); callback->addConversation(conversation); } diff --git a/src/messaging/email_manager.h b/src/messaging/email_manager.h index e6e8c1d..a591e1d 100644 --- a/src/messaging/email_manager.h +++ b/src/messaging/email_manager.h @@ -57,8 +57,10 @@ class MessageBodyCallbackData; class EmailManager { public: - static EmailManager& getInstance(); - static common::PlatformResult InitializeEmailService(); + EmailManager(); + virtual ~EmailManager(); + + common::PlatformResult InitializeEmailService(); void addDraftMessage(MessageCallbackUserData* callback); void removeMessages(MessagesCallbackUserData* callback); @@ -94,10 +96,6 @@ class EmailManager { long getUniqueOpId(); private: - EmailManager(); - EmailManager(const EmailManager&); - void operator=(const EmailManager&); - virtual ~EmailManager(); common::PlatformResult addDraftMessagePlatform(int account_id, std::shared_ptr message); common::PlatformResult addOutboxMessagePlatform(int account_id, std::shared_ptr message); common::PlatformResult addMessagePlatform(int account_id, std::shared_ptr message, diff --git a/src/messaging/find_msg_callback_user_data.cc b/src/messaging/find_msg_callback_user_data.cc index 2b309a2..f09e223 100644 --- a/src/messaging/find_msg_callback_user_data.cc +++ b/src/messaging/find_msg_callback_user_data.cc @@ -23,8 +23,9 @@ namespace extension { namespace messaging { -FindMsgCallbackUserData::FindMsgCallbackUserData(PostQueue& queue, long cid) - : CallbackUserData(queue, cid), +FindMsgCallbackUserData::FindMsgCallbackUserData(PostQueue& queue, long cid, + MessagingInstance& instance) + : CallbackUserData(queue, cid, instance), m_limit(0), m_offset(0), m_account_id(0), diff --git a/src/messaging/find_msg_callback_user_data.h b/src/messaging/find_msg_callback_user_data.h index da7f194..8445653 100644 --- a/src/messaging/find_msg_callback_user_data.h +++ b/src/messaging/find_msg_callback_user_data.h @@ -40,7 +40,7 @@ class Message; class FindMsgCallbackUserData : public CallbackUserData { public: - FindMsgCallbackUserData(PostQueue& queue, long cid); + FindMsgCallbackUserData(PostQueue& queue, long cid, MessagingInstance& instance); virtual ~FindMsgCallbackUserData(); void setFilter(AbstractFilterPtr filter); diff --git a/src/messaging/folders_change_callback.cc b/src/messaging/folders_change_callback.cc index 59c159b..6ceda0b 100644 --- a/src/messaging/folders_change_callback.cc +++ b/src/messaging/folders_change_callback.cc @@ -28,8 +28,8 @@ const char* FOLDERSUPDATED = "foldersupdated"; const char* FOLDERSREMOVED = "foldersremoved"; FoldersChangeCallback::FoldersChangeCallback(long cid, int service_id, MessageType service_type, - PostQueue& queue) - : m_callback_data(queue, cid, true), + PostQueue& queue, MessagingInstance& instance) + : m_callback_data(queue, cid, instance, true), m_id(service_id), m_msg_type(service_type), m_is_act(true) { diff --git a/src/messaging/folders_change_callback.h b/src/messaging/folders_change_callback.h index f6649a0..1b870ec 100644 --- a/src/messaging/folders_change_callback.h +++ b/src/messaging/folders_change_callback.h @@ -37,7 +37,8 @@ class FoldersChangeCallback { public: typedef void (FoldersChangeCallback::*Signature)(const FolderPtrVector& conversations); - FoldersChangeCallback(long cid, int service_id, MessageType service_type, PostQueue& queue); + FoldersChangeCallback(long cid, int service_id, MessageType service_type, PostQueue& queue, + MessagingInstance& instance); virtual ~FoldersChangeCallback(); void added(const FolderPtrVector& folders); diff --git a/src/messaging/message.cc b/src/messaging/message.cc index a171c9a..d439357 100644 --- a/src/messaging/message.cc +++ b/src/messaging/message.cc @@ -29,6 +29,7 @@ #include "message_email.h" #include "message_mms.h" #include "message_sms.h" +#include "messaging_instance.h" #include "messaging_util.h" #include "short_message_manager.h" @@ -1476,10 +1477,11 @@ PlatformResult Message::convertPlatformShortMessageToObject(msg_struct_t msg, return PlatformResult(ErrorCode::NO_ERROR); } -PlatformResult Message::findShortMessageById(const int id, MessagePtr* message) { +PlatformResult Message::findShortMessageById(const int id, MessagingInstance& instance, + MessagePtr* message) { ScopeLogger(); msg_struct_t msg; - PlatformResult ret = ShortMsgManager::getInstance().getMessage(id, &msg); + PlatformResult ret = instance.getShortMsgManager().getMessage(id, &msg); if (ret.IsError()) { return ret; } diff --git a/src/messaging/message.h b/src/messaging/message.h index 87578ea..c4c5c15 100644 --- a/src/messaging/message.h +++ b/src/messaging/message.h @@ -145,7 +145,8 @@ class Message : public FilterableObject { // function for filling Message attributes static common::PlatformResult convertPlatformShortMessageToObject(msg_struct_t msg, Message** message); - static common::PlatformResult findShortMessageById(const int id, MessagePtr* message); + static common::PlatformResult findShortMessageById(const int id, MessagingInstance& instance, + MessagePtr* message); static common::PlatformResult addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVector& attach, msg_struct_t& mms_struct, Message* message); diff --git a/src/messaging/message_callback_user_data.cc b/src/messaging/message_callback_user_data.cc index bb6f1b9..d00c46b 100644 --- a/src/messaging/message_callback_user_data.cc +++ b/src/messaging/message_callback_user_data.cc @@ -20,8 +20,9 @@ namespace extension { namespace messaging { -MessageCallbackUserData::MessageCallbackUserData(PostQueue& queue, long cid) - : CallbackUserData(queue, cid), m_account_id(0) { +MessageCallbackUserData::MessageCallbackUserData(PostQueue& queue, long cid, + MessagingInstance& instance) + : CallbackUserData(queue, cid, instance), m_account_id(0) { ScopeLogger(); } diff --git a/src/messaging/message_callback_user_data.h b/src/messaging/message_callback_user_data.h index c1f7c1a..5360f93 100644 --- a/src/messaging/message_callback_user_data.h +++ b/src/messaging/message_callback_user_data.h @@ -31,7 +31,7 @@ class PostQueue; class MessageCallbackUserData : public CallbackUserData { public: - MessageCallbackUserData(PostQueue& queue, long cid); + MessageCallbackUserData(PostQueue& queue, long cid, MessagingInstance& instance); virtual ~MessageCallbackUserData(); void setMessage(std::shared_ptr message); diff --git a/src/messaging/message_service.cc b/src/messaging/message_service.cc index aa922a5..6f683e6 100644 --- a/src/messaging/message_service.cc +++ b/src/messaging/message_service.cc @@ -41,8 +41,9 @@ const char* JSON_SERVICE_NAME = "name"; //#################### MessageRecipientsCallbackData #################### -MessageRecipientsCallbackData::MessageRecipientsCallbackData(PostQueue& queue, long cid) - : CallbackUserData(queue, cid), +MessageRecipientsCallbackData::MessageRecipientsCallbackData(PostQueue& queue, long cid, + MessagingInstance& instance) + : CallbackUserData(queue, cid, instance), m_account_id(-1), m_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN), m_default_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN) { @@ -122,8 +123,9 @@ TelNetworkDefaultDataSubs_t MessageRecipientsCallbackData::getDefaultSimIndex() //#################### BaseMessageServiceCallbackData #################### -BaseMessageServiceCallbackData::BaseMessageServiceCallbackData(PostQueue& queue, long cid) - : CallbackUserData(queue, cid), m_op_handle(-1) { +BaseMessageServiceCallbackData::BaseMessageServiceCallbackData(PostQueue& queue, long cid, + MessagingInstance& instance) + : CallbackUserData(queue, cid, instance), m_op_handle(-1) { ScopeLogger(); } @@ -155,8 +157,9 @@ std::shared_ptr MessageBodyCallbackData::getMessage() const { //#################### MessageAttachmentCallbackData #################### -MessageAttachmentCallbackData::MessageAttachmentCallbackData(PostQueue& queue, long cid) - : BaseMessageServiceCallbackData(queue, cid), m_nth(0) { +MessageAttachmentCallbackData::MessageAttachmentCallbackData(PostQueue& queue, long cid, + MessagingInstance& instance) + : BaseMessageServiceCallbackData(queue, cid, instance), m_nth(0) { ScopeLogger(); } @@ -183,8 +186,8 @@ int MessageAttachmentCallbackData::getNth() const { //#################### SyncCallbackData #################### -SyncCallbackData::SyncCallbackData(PostQueue& queue, long cid) - : BaseMessageServiceCallbackData(queue, cid), +SyncCallbackData::SyncCallbackData(PostQueue& queue, long cid, MessagingInstance& instance) + : BaseMessageServiceCallbackData(queue, cid, instance), m_is_limit(false), m_limit(0), m_op_id(-1), @@ -241,8 +244,9 @@ std::shared_ptr SyncFolderCallbackData::getMessageFolder() const //#################### MessageService #################### -MessageService::MessageService(int id, MessageType msgType, const std::string& name) - : m_id(id), m_msg_type(msgType), m_name(name) { +MessageService::MessageService(int id, MessageType msgType, const std::string& name, + MessagingInstance& instance) + : m_id(id), m_msg_type(msgType), m_name(name), instance_(instance) { ScopeLogger(); switch (msgType) { case MessageType::SMS: diff --git a/src/messaging/message_service.h b/src/messaging/message_service.h index e0e888e..ca16baf 100644 --- a/src/messaging/message_service.h +++ b/src/messaging/message_service.h @@ -36,7 +36,7 @@ enum MessageServiceAccountId { UNKNOWN_ACCOUNT_ID = 0, SMS_ACCOUNT_ID = 101, MMS class MessageRecipientsCallbackData : public CallbackUserData { public: - MessageRecipientsCallbackData(PostQueue& queue, long cid); + MessageRecipientsCallbackData(PostQueue& queue, long cid, MessagingInstance& instance); virtual ~MessageRecipientsCallbackData(); void setMessage(std::shared_ptr message); @@ -64,7 +64,7 @@ class MessageRecipientsCallbackData : public CallbackUserData { class BaseMessageServiceCallbackData : public CallbackUserData { public: - BaseMessageServiceCallbackData(PostQueue& queue, long cid); + BaseMessageServiceCallbackData(PostQueue& queue, long cid, MessagingInstance& instance); virtual ~BaseMessageServiceCallbackData(); /** @@ -96,7 +96,7 @@ class MessageBodyCallbackData : public BaseMessageServiceCallbackData { class MessageAttachmentCallbackData : public BaseMessageServiceCallbackData { public: - MessageAttachmentCallbackData(PostQueue& queue, long cid); + MessageAttachmentCallbackData(PostQueue& queue, long cid, MessagingInstance& instance); virtual ~MessageAttachmentCallbackData(); void setMessageAttachment(std::shared_ptr messageAttachment); @@ -119,7 +119,7 @@ class MessageAttachmentCallbackData : public BaseMessageServiceCallbackData { class SyncCallbackData : public BaseMessageServiceCallbackData { public: - SyncCallbackData(PostQueue& queue, long cid); + SyncCallbackData(PostQueue& queue, long cid, MessagingInstance& instance); virtual ~SyncCallbackData(); void setLimit(const unsigned long limit); @@ -177,12 +177,13 @@ class MessageService { * We have child classes MessageServiceEmail and MessageServiceShortMsg which * should provide specialized implementation. */ - MessageService(int id, MessageType msgType, const std::string& name); + MessageService(int id, MessageType msgType, const std::string& name, MessagingInstance& instance); int m_id; MessageType m_msg_type; std::string m_name; MessageStoragePtr m_storage; + MessagingInstance& instance_; }; } // messaging diff --git a/src/messaging/message_service_email.cc b/src/messaging/message_service_email.cc index 09b941e..9a8a874 100644 --- a/src/messaging/message_service_email.cc +++ b/src/messaging/message_service_email.cc @@ -16,6 +16,7 @@ #include "message_service_email.h" #include "email_manager.h" +#include "messaging_instance.h" #include "common/logger.h" @@ -25,8 +26,8 @@ using common::PlatformResult; namespace extension { namespace messaging { -MessageServiceEmail::MessageServiceEmail(int id, std::string name) - : MessageService(id, MessageType::EMAIL, name) { +MessageServiceEmail::MessageServiceEmail(int id, std::string name, MessagingInstance& instance) + : MessageService(id, MessageType::EMAIL, name, instance) { ScopeLogger(); } @@ -36,15 +37,14 @@ MessageServiceEmail::~MessageServiceEmail() { for (auto id : registered_callbacks_) { // this may internally fail, because we don't have information about // callbacks which already have fired - EmailManager::getInstance().RemoveSyncCallback(id); + instance_.getEmailManager().RemoveSyncCallback(id); } } static gboolean sendMessageTask(void* data) { ScopeLogger(); - - auto ret = - EmailManager::getInstance().sendMessage(static_cast(data)); + MessageRecipientsCallbackData* callback = static_cast(data); + auto ret = callback->getEmailManager().sendMessage(callback); if (!ret) { LoggerE("Error: %d - %s", ret.error_code(), ret.message().c_str()); @@ -73,8 +73,8 @@ PlatformResult MessageServiceEmail::sendMessage(MessageRecipientsCallbackData* c static gboolean loadMessageBodyTask(void* data) { ScopeLogger(); - - EmailManager::getInstance().loadMessageBody(static_cast(data)); + MessageBodyCallbackData* callback = static_cast(data); + callback->getEmailManager().loadMessageBody(callback); return FALSE; } @@ -113,7 +113,7 @@ static gboolean loadMessageAttachmentTask(void* data) { delete callback; callback = nullptr; } else { - const auto ret = EmailManager::getInstance().loadMessageAttachment(callback); + const auto ret = callback->getEmailManager().loadMessageAttachment(callback); if (!ret) { LoggerE("Error: %d - %s", ret.error_code(), ret.message().c_str()); @@ -138,8 +138,8 @@ PlatformResult MessageServiceEmail::loadMessageAttachment(MessageAttachmentCallb static gboolean syncTask(void* data) { ScopeLogger(); - - EmailManager::getInstance().sync(data); + SyncCallbackData* callback = static_cast(data); + callback->getEmailManager().sync(data); return FALSE; } @@ -151,7 +151,7 @@ PlatformResult MessageServiceEmail::sync(SyncCallbackData* callback, long* opera return LogAndCreateResult(ErrorCode::UNKNOWN_ERR, "Callback is null"); } - long op_id = EmailManager::getInstance().getUniqueOpId(); + long op_id = callback->getEmailManager().getUniqueOpId(); callback->setOpId(op_id); guint id = g_idle_add(syncTask, static_cast(callback)); @@ -166,8 +166,8 @@ PlatformResult MessageServiceEmail::sync(SyncCallbackData* callback, long* opera static gboolean syncFolderTask(void* data) { ScopeLogger(); - - EmailManager::getInstance().syncFolder(static_cast(data)); + SyncFolderCallbackData* callback = static_cast(data); + callback->getEmailManager().syncFolder(callback); return FALSE; } @@ -184,7 +184,7 @@ PlatformResult MessageServiceEmail::syncFolder(SyncFolderCallbackData* callback, return LogAndCreateResult(ErrorCode::TYPE_MISMATCH_ERR, "Message folder is null"); } - long op_id = EmailManager::getInstance().getUniqueOpId(); + long op_id = callback->getEmailManager().getUniqueOpId(); callback->setOpId(op_id); guint id = g_idle_add(syncFolderTask, callback); @@ -205,11 +205,11 @@ static gboolean stopSyncTask(void* data) { return FALSE; } - const long op_id = *(static_cast(data)); - delete static_cast(data); - data = NULL; - EmailManager::getInstance().stopSync(op_id); - + StopSyncData* callback = static_cast(data); + long op_id = callback->op_id; + callback->instance.getEmailManager().stopSync(op_id); + delete callback; + callback = nullptr; return FALSE; } @@ -217,7 +217,7 @@ PlatformResult MessageServiceEmail::stopSync(long op_id) { ScopeLogger(); registered_callbacks_.erase(op_id); - long* data = new long(op_id); + StopSyncData* data = new StopSyncData{op_id, instance_}; guint id = g_idle_add(stopSyncTask, static_cast(data)); if (!id) { diff --git a/src/messaging/message_service_email.h b/src/messaging/message_service_email.h index 8d14bb7..e169110 100644 --- a/src/messaging/message_service_email.h +++ b/src/messaging/message_service_email.h @@ -24,9 +24,14 @@ namespace extension { namespace messaging { +struct StopSyncData { + long op_id; + MessagingInstance& instance; +}; + class MessageServiceEmail : public MessageService { public: - MessageServiceEmail(int id, std::string name); + MessageServiceEmail(int id, std::string name, MessagingInstance& instance); virtual ~MessageServiceEmail(); virtual common::PlatformResult sendMessage(MessageRecipientsCallbackData* callback); diff --git a/src/messaging/message_service_short_msg.cc b/src/messaging/message_service_short_msg.cc index 78db705..a5ca744 100644 --- a/src/messaging/message_service_short_msg.cc +++ b/src/messaging/message_service_short_msg.cc @@ -37,8 +37,9 @@ using common::PlatformResult; namespace extension { namespace messaging { -MessageServiceShortMsg::MessageServiceShortMsg(int id, MessageType msgType) - : MessageService(id, msgType, MessagingUtil::messageTypeToString(msgType)) { +MessageServiceShortMsg::MessageServiceShortMsg(int id, MessageType msgType, + MessagingInstance& instance) + : MessageService(id, msgType, MessagingUtil::messageTypeToString(msgType), instance) { ScopeLogger(); } @@ -49,8 +50,8 @@ MessageServiceShortMsg::~MessageServiceShortMsg() { static gboolean sendMessageThread(void* data) { ScopeLogger(); - auto ret = - ShortMsgManager::getInstance().sendMessage(static_cast(data)); + MessageRecipientsCallbackData* callback = static_cast(data); + auto ret = callback->getShortMsgManager().sendMessage(callback); if (!ret) { LoggerE("Error: %d - %s", ret.error_code(), ret.message().c_str()); @@ -150,16 +151,16 @@ PlatformResult MessageServiceShortMsg::loadMessageBody(MessageBodyCallbackData* return PlatformResult(ErrorCode::NO_ERROR); } -MessageServiceShortMsg* MessageServiceShortMsg::GetMmsMessageService() { +MessageServiceShortMsg* MessageServiceShortMsg::GetMmsMessageService(MessagingInstance& instance) { ScopeLogger(); return new (std::nothrow) - MessageServiceShortMsg(MessageServiceAccountId::MMS_ACCOUNT_ID, MessageType::MMS); + MessageServiceShortMsg(MessageServiceAccountId::MMS_ACCOUNT_ID, MessageType::MMS, instance); } -MessageServiceShortMsg* MessageServiceShortMsg::GetSmsMessageService() { +MessageServiceShortMsg* MessageServiceShortMsg::GetSmsMessageService(MessagingInstance& instance) { ScopeLogger(); return new (std::nothrow) - MessageServiceShortMsg(MessageServiceAccountId::SMS_ACCOUNT_ID, MessageType::SMS); + MessageServiceShortMsg(MessageServiceAccountId::SMS_ACCOUNT_ID, MessageType::SMS, instance); } } // namespace messaging diff --git a/src/messaging/message_service_short_msg.h b/src/messaging/message_service_short_msg.h index d1ad5f2..a18c40a 100644 --- a/src/messaging/message_service_short_msg.h +++ b/src/messaging/message_service_short_msg.h @@ -31,11 +31,11 @@ class MessageServiceShortMsg : public MessageService { virtual common::PlatformResult loadMessageBody(MessageBodyCallbackData* callback); - static MessageServiceShortMsg* GetMmsMessageService(); - static MessageServiceShortMsg* GetSmsMessageService(); + static MessageServiceShortMsg* GetMmsMessageService(MessagingInstance& instance); + static MessageServiceShortMsg* GetSmsMessageService(MessagingInstance& instance); protected: - MessageServiceShortMsg(int id, MessageType msgType); + MessageServiceShortMsg(int id, MessageType msgType, MessagingInstance& instance); }; } // namespace messaging diff --git a/src/messaging/message_storage_email.cc b/src/messaging/message_storage_email.cc index 87e670c..fc5bfa0 100644 --- a/src/messaging/message_storage_email.cc +++ b/src/messaging/message_storage_email.cc @@ -22,6 +22,7 @@ #include "email_manager.h" #include "message.h" +#include "messaging_instance.h" namespace extension { namespace messaging { @@ -38,7 +39,7 @@ static gboolean addDraftMessageTask(void* data) { ScopeLogger(); MessageCallbackUserData* callback = static_cast(data); - EmailManager::getInstance().addDraftMessage(callback); + callback->getEmailManager().addDraftMessage(callback); return FALSE; } @@ -65,7 +66,7 @@ static gboolean removeMessagesTask(void* data) { ScopeLogger(); MessagesCallbackUserData* callback = static_cast(data); - EmailManager::getInstance().removeMessages(callback); + callback->getEmailManager().removeMessages(callback); return FALSE; } @@ -92,7 +93,7 @@ static gboolean updateMessagesTask(void* data) { ScopeLogger(); MessagesCallbackUserData* callback = static_cast(data); - EmailManager::getInstance().updateMessages(callback); + callback->getEmailManager().updateMessages(callback); return FALSE; } @@ -118,7 +119,7 @@ static gboolean findMessagesTask(void* data) { ScopeLogger(); FindMsgCallbackUserData* callback = static_cast(data); - EmailManager::getInstance().findMessages(callback); + callback->getEmailManager().findMessages(callback); return FALSE; } @@ -146,7 +147,7 @@ static gboolean findConversationsTask(void* data) { ScopeLogger(); ConversationCallbackData* callback = static_cast(data); - EmailManager::getInstance().findConversations(callback); + callback->getEmailManager().findConversations(callback); return FALSE; } @@ -173,7 +174,7 @@ static gboolean removeConversationsTask(void* data) { ScopeLogger(); ConversationCallbackData* callback = static_cast(data); - EmailManager::getInstance().removeConversations(callback); + callback->getEmailManager().removeConversations(callback); return FALSE; } @@ -200,7 +201,7 @@ static gboolean findFoldersTask(void* data) { ScopeLogger(); FoldersCallbackData* callback = static_cast(data); - EmailManager::getInstance().findFolders(callback); + callback->getEmailManager().findFolders(callback); return FALSE; } diff --git a/src/messaging/message_storage_short_msg.cc b/src/messaging/message_storage_short_msg.cc index 335b189..2c1e472 100644 --- a/src/messaging/message_storage_short_msg.cc +++ b/src/messaging/message_storage_short_msg.cc @@ -39,7 +39,7 @@ static gboolean addDraftMessageTask(void* data) { ScopeLogger(); MessageCallbackUserData* callback = static_cast(data); - ShortMsgManager::getInstance().addDraftMessage(callback); + callback->getShortMsgManager().addDraftMessage(callback); return false; } @@ -64,7 +64,7 @@ static gboolean removeMessagesTask(void* data) { ScopeLogger(); MessagesCallbackUserData* callback = static_cast(data); - ShortMsgManager::getInstance().removeMessages(callback); + callback->getShortMsgManager().removeMessages(callback); return false; } @@ -91,7 +91,7 @@ static gboolean updateMessagesTask(void* data) { ScopeLogger(); MessagesCallbackUserData* callback = static_cast(data); - ShortMsgManager::getInstance().updateMessages(callback); + callback->getShortMsgManager().updateMessages(callback); return false; } @@ -118,7 +118,7 @@ static gboolean findMessagesTask(void* data) { ScopeLogger(); FindMsgCallbackUserData* callback = static_cast(data); - ShortMsgManager::getInstance().findMessages(callback); + callback->getShortMsgManager().findMessages(callback); return false; } @@ -145,7 +145,7 @@ static gboolean findConversationsTask(void* data) { ScopeLogger(); ConversationCallbackData* callback = static_cast(data); - ShortMsgManager::getInstance().findConversations(callback); + callback->getShortMsgManager().findConversations(callback); return false; } @@ -172,7 +172,7 @@ static gboolean removeConversationsTask(void* data) { ScopeLogger(); ConversationCallbackData* callback = static_cast(data); - ShortMsgManager::getInstance().removeConversations(callback); + callback->getShortMsgManager().removeConversations(callback); return false; } diff --git a/src/messaging/messages_callback_user_data.cc b/src/messaging/messages_callback_user_data.cc index ef74d62..b847468 100644 --- a/src/messaging/messages_callback_user_data.cc +++ b/src/messaging/messages_callback_user_data.cc @@ -20,8 +20,9 @@ namespace extension { namespace messaging { MessagesCallbackUserData::MessagesCallbackUserData(PostQueue& queue, long cid, + MessagingInstance& instance, bool keep /* = false*/) - : CallbackUserData(queue, cid, keep), m_service_type(UNDEFINED) { + : CallbackUserData(queue, cid, instance, keep), m_service_type(UNDEFINED) { ScopeLogger(); } diff --git a/src/messaging/messages_callback_user_data.h b/src/messaging/messages_callback_user_data.h index e59b100..4869cce 100644 --- a/src/messaging/messages_callback_user_data.h +++ b/src/messaging/messages_callback_user_data.h @@ -32,7 +32,8 @@ class Message; class MessagesCallbackUserData : public CallbackUserData { public: - MessagesCallbackUserData(PostQueue& queue, long cid, bool keep = false); + MessagesCallbackUserData(PostQueue& queue, long cid, MessagingInstance& instance, + bool keep = false); virtual ~MessagesCallbackUserData(); void addMessage(std::shared_ptr msg); diff --git a/src/messaging/messages_change_callback.cc b/src/messaging/messages_change_callback.cc index d262a42..d476d9c 100644 --- a/src/messaging/messages_change_callback.cc +++ b/src/messaging/messages_change_callback.cc @@ -47,8 +47,8 @@ const char* MESSAGESUPDATED = "messagesupdated"; const char* MESSAGESREMOVED = "messagesremoved"; MessagesChangeCallback::MessagesChangeCallback(long cid, int service_id, MessageType service_type, - PostQueue& queue) - : m_callback_data(queue, cid, true), + PostQueue& queue, MessagingInstance& instance) + : m_callback_data(queue, cid, instance, true), m_service_id(service_id), m_msg_type(service_type), m_is_act(true) { diff --git a/src/messaging/messages_change_callback.h b/src/messaging/messages_change_callback.h index 64343cb..fe721be 100644 --- a/src/messaging/messages_change_callback.h +++ b/src/messaging/messages_change_callback.h @@ -38,7 +38,8 @@ class MessagesChangeCallback { public: typedef void (MessagesChangeCallback::*Signature)(const MessagePtrVector& conversations); - MessagesChangeCallback(long cid, int service_id, MessageType service_type, PostQueue& queue); + MessagesChangeCallback(long cid, int service_id, MessageType service_type, PostQueue& queue, + MessagingInstance& instance); virtual ~MessagesChangeCallback(); void added(const MessagePtrVector& messages); diff --git a/src/messaging/messaging_extension.cc b/src/messaging/messaging_extension.cc index caefca7..97e5e9a 100644 --- a/src/messaging/messaging_extension.cc +++ b/src/messaging/messaging_extension.cc @@ -47,10 +47,11 @@ MessagingExtension::~MessagingExtension() { common::Instance* MessagingExtension::CreateInstance() { ScopeLogger(); - PlatformResult ret = extension::messaging::EmailManager::InitializeEmailService(); + extension::messaging::MessagingInstance* instance = new extension::messaging::MessagingInstance(); + PlatformResult ret = instance->getEmailManager().InitializeEmailService(); if (ret.IsError()) { LoggerE("Initializing the email service failed (%s)", ret.message().c_str()); return nullptr; } - return new extension::messaging::MessagingInstance(); + return static_cast(instance); } diff --git a/src/messaging/messaging_instance.cc b/src/messaging/messaging_instance.cc index 1446c73..2cf41a5 100644 --- a/src/messaging/messaging_instance.cc +++ b/src/messaging/messaging_instance.cc @@ -174,6 +174,14 @@ MessagingInstance::~MessagingInstance() { return; \ } +EmailManager& MessagingInstance::getEmailManager() { + return email_manager_; +} + +ShortMsgManager& MessagingInstance::getShortMsgManager() { + return short_msg_manager_; +} + void MessagingInstance::GetMessageServices(const picojson::value& args, picojson::object& out) { ScopeLogger(); @@ -202,12 +210,13 @@ void MessagingInstance::MessageServiceSendMessage(const picojson::value& args, obj[JSON_CALLBACK_ID] = picojson::value(callbackId); std::shared_ptr message; - PlatformResult ret = MessagingUtil::jsonToMessage(v_message, &message); + PlatformResult ret = MessagingUtil::jsonToMessage(v_message, &message, *this); if (ret.IsError()) { POST_AND_RETURN(ret, json, obj) } - MessageRecipientsCallbackData* callback = new MessageRecipientsCallbackData(queue_, callbackId); + MessageRecipientsCallbackData* callback = + new MessageRecipientsCallbackData(queue_, callbackId, *this); long simIndex = 0; int serviceId = 0; @@ -256,12 +265,12 @@ void MessagingInstance::MessageServiceLoadMessageBody(const picojson::value& arg obj[JSON_CALLBACK_ID] = picojson::value(callbackId); std::shared_ptr message; - PlatformResult ret = MessagingUtil::jsonToMessage(json_message, &message); + PlatformResult ret = MessagingUtil::jsonToMessage(json_message, &message, *this); if (ret.IsError()) { POST_AND_RETURN(ret, json, obj) } - MessageBodyCallbackData* callback = new MessageBodyCallbackData(queue_, callbackId); + MessageBodyCallbackData* callback = new MessageBodyCallbackData(queue_, callbackId, *this); callback->setMessage(message); @@ -284,7 +293,8 @@ void MessagingInstance::MessageServiceLoadMessageAttachment(const picojson::valu picojson::value attachment = data.at(LOAD_MESSAGE_ATTACHMENT_ARGS_ATTACHMENT); const double callbackId = args.get(JSON_CALLBACK_ID).get(); - MessageAttachmentCallbackData* callback = new MessageAttachmentCallbackData(queue_, callbackId); + MessageAttachmentCallbackData* callback = + new MessageAttachmentCallbackData(queue_, callbackId, *this); callback->setMessageAttachment(MessagingUtil::jsonToMessageAttachment(attachment)); callback->AddToQueue(); @@ -322,7 +332,7 @@ void MessagingInstance::MessageServiceSync(const picojson::value& args, picojson limit = static_cast(v_limit.get()); } - SyncCallbackData* callback = new SyncCallbackData(queue_, callbackId); + SyncCallbackData* callback = new SyncCallbackData(queue_, callbackId, *this); callback->setAccountId(id); callback->setLimit(limit); @@ -365,7 +375,7 @@ void MessagingInstance::MessageServiceSyncFolder(const picojson::value& args, limit = static_cast(v_limit.get()); } - SyncFolderCallbackData* callback = new SyncFolderCallbackData(queue_, callbackId); + SyncFolderCallbackData* callback = new SyncFolderCallbackData(queue_, callbackId, *this); callback->setAccountId(id); callback->setMessageFolder(MessagingUtil::jsonToMessageFolder(v_folder)); callback->setLimit(limit); @@ -432,12 +442,12 @@ void MessagingInstance::MessageStorageAddDraft(const picojson::value& args, pico obj[JSON_CALLBACK_ID] = picojson::value(callbackId); std::shared_ptr message; - PlatformResult ret = MessagingUtil::jsonToMessage(v_message, &message); + PlatformResult ret = MessagingUtil::jsonToMessage(v_message, &message, *this); if (ret.IsError()) { POST_AND_RETURN(ret, json, obj) } - MessageCallbackUserData* callback = new MessageCallbackUserData(queue_, callbackId); + MessageCallbackUserData* callback = new MessageCallbackUserData(queue_, callbackId, *this); callback->setMessage(message); int serviceId = getServiceIdFromJSON(data); @@ -478,7 +488,7 @@ void MessagingInstance::MessageStorageFindMessages(const picojson::value& args, int serviceId = getServiceIdFromJSON(data); auto storage = manager_.getMessageService(serviceId)->getMsgStorage(); - FindMsgCallbackUserData* callback = new FindMsgCallbackUserData(queue_, callbackId); + FindMsgCallbackUserData* callback = new FindMsgCallbackUserData(queue_, callbackId, *this); callback->setFilter(filter); callback->setLimit(limit); callback->setOffset(offset); @@ -500,11 +510,11 @@ void MessagingInstance::MessageStorageRemoveMessages(const picojson::value& args picojson::array messages = data.at(REMOVE_MESSAGES_ARGS_MESSAGES).get(); const double callbackId = args.get(JSON_CALLBACK_ID).get(); - MessagesCallbackUserData* callback = new MessagesCallbackUserData(queue_, callbackId); + MessagesCallbackUserData* callback = new MessagesCallbackUserData(queue_, callbackId, *this); - auto each = [callback](picojson::value& v) -> void { + auto each = [callback, this](picojson::value& v) -> void { std::shared_ptr message; - PlatformResult ret = MessagingUtil::jsonToMessage(v, &message); + PlatformResult ret = MessagingUtil::jsonToMessage(v, &message, *this); if (ret.IsSuccess()) { callback->addMessage(message); } @@ -530,15 +540,16 @@ void MessagingInstance::MessageStorageUpdateMessages(const picojson::value& args auto pico_array = pico_messages.get(); const double callbackId = args.get(JSON_CALLBACK_ID).get(); - auto callback = new MessagesCallbackUserData(queue_, callbackId); + auto callback = new MessagesCallbackUserData(queue_, callbackId, *this); - std::for_each(pico_array.begin(), pico_array.end(), [&callback](picojson::value& v) -> void { - std::shared_ptr message; - PlatformResult ret = MessagingUtil::jsonToMessage(v, &message); - if (ret.IsSuccess()) { - callback->addMessage(message); - } - }); + std::for_each(pico_array.begin(), pico_array.end(), + [&callback, this](picojson::value& v) -> void { + std::shared_ptr message; + PlatformResult ret = MessagingUtil::jsonToMessage(v, &message, *this); + if (ret.IsSuccess()) { + callback->addMessage(message); + } + }); auto service = manager_.getMessageService(getServiceIdFromJSON(data)); @@ -573,7 +584,7 @@ void MessagingInstance::MessageStorageFindConversations(const picojson::value& a int serviceId = getServiceIdFromJSON(data); - ConversationCallbackData* callback = new ConversationCallbackData(queue_, callbackId); + ConversationCallbackData* callback = new ConversationCallbackData(queue_, callbackId, *this); callback->setFilter(filter); callback->setLimit(limit); callback->setOffset(offset); @@ -601,7 +612,7 @@ void MessagingInstance::MessageStorageRemoveConversations(const picojson::value& picojson::object& obj = json->get(); obj[JSON_CALLBACK_ID] = picojson::value(callbackId); - ConversationCallbackData* callback = new ConversationCallbackData(queue_, callbackId); + ConversationCallbackData* callback = new ConversationCallbackData(queue_, callbackId, *this); PlatformResult ret(ErrorCode::NO_ERROR); for (auto it = conversations.begin(); it != conversations.end(); ++it) { @@ -640,7 +651,7 @@ void MessagingInstance::MessageStorageFindFolders(const picojson::value& args, POST_AND_RETURN(ret, json, obj) } - FoldersCallbackData* callback = new FoldersCallbackData(queue_, callbackId); + FoldersCallbackData* callback = new FoldersCallbackData(queue_, callbackId, *this); callback->setFilter(filter); callback->AddToQueue(); @@ -667,8 +678,8 @@ void MessagingInstance::MessageStorageAddMessagesChangeListener(const picojson:: auto service = manager_.getMessageService(serviceId); - std::shared_ptr callback( - new MessagesChangeCallback(kDumbCallbackId, serviceId, service->getMsgServiceType(), queue_)); + std::shared_ptr callback(new MessagesChangeCallback( + kDumbCallbackId, serviceId, service->getMsgServiceType(), queue_, *this)); callback->setFilter(filter); @@ -698,7 +709,7 @@ void MessagingInstance::MessageStorageAddConversationsChangeListener(const picoj auto service = manager_.getMessageService(serviceId); std::shared_ptr callback(new ConversationsChangeCallback( - static_cast(-1), serviceId, service->getMsgServiceType(), queue_)); + static_cast(-1), serviceId, service->getMsgServiceType(), queue_, *this)); callback->setFilter(filter); @@ -728,7 +739,7 @@ void MessagingInstance::MessageStorageAddFolderChangeListener(const picojson::va auto service = manager_.getMessageService(serviceId); std::shared_ptr callback(new FoldersChangeCallback( - static_cast(-1), serviceId, service->getMsgServiceType(), queue_)); + static_cast(-1), serviceId, service->getMsgServiceType(), queue_, *this)); callback->setFilter(filter); @@ -764,9 +775,9 @@ void MessagingInstance::MessageGetMessageStatus(const picojson::value& args, std::string status; if (FUN_MESSAGE_MESSAGING_EMAIL == type) { - status = EmailManager::getInstance().getMessageStatus(id); + status = email_manager_.getMessageStatus(id); } else { - status = ShortMsgManager::getInstance().getMessageStatus(id); + status = short_msg_manager_.getMessageStatus(id); } ReportSuccess(picojson::value(status), out); diff --git a/src/messaging/messaging_instance.h b/src/messaging/messaging_instance.h index 531af88..d5ff5d7 100644 --- a/src/messaging/messaging_instance.h +++ b/src/messaging/messaging_instance.h @@ -19,8 +19,10 @@ #include "common/extension.h" +#include "email_manager.h" #include "messaging_manager.h" #include "messaging_util.h" +#include "short_message_manager.h" namespace extension { namespace messaging { @@ -29,6 +31,8 @@ class MessagingInstance : public common::ParsedInstance { public: MessagingInstance(); virtual ~MessagingInstance(); + EmailManager& getEmailManager(); + ShortMsgManager& getShortMsgManager(); private: void GetMessageServices(const picojson::value& args, picojson::object& out); @@ -55,6 +59,8 @@ class MessagingInstance : public common::ParsedInstance { void MessageGetMessageStatus(const picojson::value& args, picojson::object& out); MessagingManager manager_; + ShortMsgManager short_msg_manager_; + EmailManager email_manager_; PostQueue queue_; }; diff --git a/src/messaging/messaging_manager.cc b/src/messaging/messaging_manager.cc index 3016ff9..dbb4f4c 100644 --- a/src/messaging/messaging_manager.cc +++ b/src/messaging/messaging_manager.cc @@ -61,7 +61,7 @@ MessagingManager::MessagingManager(MessagingInstance& instance) : instance_(inst if (ret != MSG_SUCCESS) { LoggerE("Cannot get message handle: %d", ret); } else { - ShortMsgManager::getInstance().registerStatusCallback(m_msg_handle); + instance.getShortMsgManager().registerStatusCallback(m_msg_handle); } m_sms_service = std::make_pair(UNDEFINED_MESSAGE_SERVICE, nullptr); @@ -113,7 +113,8 @@ static void* getMsgServicesThread(const std::shared_ptr& delete user_data->sms_service->second; } - MessageService* service = MessageServiceShortMsg::GetSmsMessageService(); + MessageService* service = + MessageServiceShortMsg::GetSmsMessageService(user_data->instance_); if (!service) { platform_result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, @@ -138,7 +139,8 @@ static void* getMsgServicesThread(const std::shared_ptr& delete user_data->mms_service->second; } - MessageService* service = MessageServiceShortMsg::GetMmsMessageService(); + MessageService* service = + MessageServiceShortMsg::GetMmsMessageService(user_data->instance_); if (!service) { platform_result = LogAndCreateResult(ErrorCode::UNKNOWN_ERR, @@ -180,8 +182,8 @@ static void* getMsgServicesThread(const std::shared_ptr& LoggerD("Account[%d/%d] id: %d, name: %s", i, count, email_accounts[i].account_id, name.c_str()); - MessageService* service = new (std::nothrow) - MessageServiceEmail(email_accounts[i].account_id, name.c_str()); + MessageService* service = new (std::nothrow) MessageServiceEmail( + email_accounts[i].account_id, name.c_str(), user_data->instance_); if (!service) { LoggerD("message service[%d] is NULL", i); std::for_each(msgServices.begin(), msgServices.end(), diff --git a/src/messaging/messaging_util.cc b/src/messaging/messaging_util.cc index 6385c43..d919911 100644 --- a/src/messaging/messaging_util.cc +++ b/src/messaging/messaging_util.cc @@ -674,7 +674,8 @@ picojson::value MessagingUtil::folderToJson(std::shared_ptr folde } PlatformResult MessagingUtil::jsonToMessage(const picojson::value& json, - std::shared_ptr* result_message) { + std::shared_ptr* result_message, + MessagingInstance& instance) { ScopeLogger(); std::shared_ptr message; picojson::object data = json.get(); @@ -700,7 +701,7 @@ PlatformResult MessagingUtil::jsonToMessage(const picojson::value& json, } else { std::string mid = data.at(MESSAGE_ATTRIBUTE_ID).get(); int message_id = std::atoi(mid.c_str()); - platform_result = Message::findShortMessageById(message_id, &message); + platform_result = Message::findShortMessageById(message_id, instance, &message); if (!platform_result) return platform_result; } break; @@ -1143,7 +1144,7 @@ PostQueue::PostQueue(MessagingInstance& instance) : instance_(instance) { PostQueue::~PostQueue() { ScopeLogger("this: [%p]", this); - EmailManager::getInstance().RemoveCallbacksByQueue(*this); + instance_.getEmailManager().RemoveCallbacksByQueue(*this); } void PostQueue::addAndResolve(const long cid, PostPriority priority, const std::string& json) { diff --git a/src/messaging/messaging_util.h b/src/messaging/messaging_util.h index bbd8926..7ccd031 100644 --- a/src/messaging/messaging_util.h +++ b/src/messaging/messaging_util.h @@ -128,7 +128,8 @@ class MessagingUtil { static picojson::value conversationToJson(std::shared_ptr conversation); static picojson::value folderToJson(std::shared_ptr folder); static common::PlatformResult jsonToMessage(const picojson::value& json, - std::shared_ptr* result); + std::shared_ptr* result, + MessagingInstance& instance); static std::shared_ptr jsonToMessageBody(const picojson::value& json); static std::shared_ptr jsonToMessageFolder(const picojson::value& json); static tizen::SortModePtr jsonToSortMode(const picojson::object& json); diff --git a/src/messaging/short_message_manager.cc b/src/messaging/short_message_manager.cc index 8bc5468..6007a59 100644 --- a/src/messaging/short_message_manager.cc +++ b/src/messaging/short_message_manager.cc @@ -39,13 +39,6 @@ using common::PlatformResult; namespace extension { namespace messaging { -ShortMsgManager& ShortMsgManager::getInstance() { - ScopeLogger(); - - static ShortMsgManager instance; - return instance; -} - static gboolean sendMessageCompleteCB(void* data) { ScopeLogger("callback:%p", data); @@ -390,13 +383,15 @@ void ShortMsgManager::sendStatusCallback(msg_struct_t sent_status) { static void sent_status_cb(msg_handle_t handle, msg_struct_t sent_status, void* data) { ScopeLogger(); - ShortMsgManager::getInstance().sendStatusCallback(sent_status); + ShortMsgManager* short_msg_manager = static_cast(data); + short_msg_manager->sendStatusCallback(sent_status); return; } -PlatformResult ShortMsgManager::callProperEventMessages( - EventMessages* event, msg_storage_change_type_t storageChangeType) { +PlatformResult ShortMsgManager::callProperEventMessages(EventMessages* event, + msg_storage_change_type_t storageChangeType, + ShortMsgManager* shortMsgManager) { ScopeLogger( "event.items.size()=%d event.removed_conversations.size()=%d" " sChangeType:%d", @@ -410,7 +405,7 @@ PlatformResult ShortMsgManager::callProperEventMessages( eventConv->items = event->removed_conversations; } else { PlatformResult ret = ShortMsgManager::getConversationsForMessages( - event->items, storageChangeType, &(eventConv->items)); + event->items, storageChangeType, &(eventConv->items), shortMsgManager); if (ret.IsError()) { LoggerD("Error while getting conversations for message"); delete event; @@ -513,21 +508,23 @@ void ShortMsgManager::storage_change_cb(msg_handle_t handle, eventMMS->service_type = MessageType::MMS; eventMMS->service_id = MMS_ACCOUNT_ID; + ShortMsgManager* short_msg_manager = static_cast(data); + if (MSG_STORAGE_CHANGE_DELETE == storageChangeType) { - ShortMsgManager& msg_manager = ShortMsgManager::getInstance(); - std::lock_guard lock(msg_manager.m_mutex); + std::lock_guard lock(short_msg_manager->m_mutex); std::map* rem_msgs[2] = { // Recently removed messages - &msg_manager.m_sms_removed_messages, &msg_manager.m_mms_removed_messages}; + &short_msg_manager->m_sms_removed_messages, &short_msg_manager->m_mms_removed_messages}; std::map* rem_convs[2] = {// Recently removed conversations - &msg_manager.m_sms_removed_msg_id_conv_id_map, - &msg_manager.m_mms_removed_msg_id_conv_id_map}; + &short_msg_manager->m_sms_removed_msg_id_conv_id_map, + &short_msg_manager->m_mms_removed_msg_id_conv_id_map}; EventMessages* dest_event[2] = {// SMS/MMS EventMessage to be propagated eventSMS, eventMMS}; - std::map* conv_map[2] = {// Map conversationId - object - &msg_manager.m_sms_removed_conv_id_object_map, - &msg_manager.m_mms_removed_conv_id_object_map}; + std::map* conv_map[2] = { + // Map conversationId - object + &short_msg_manager->m_sms_removed_conv_id_object_map, + &short_msg_manager->m_mms_removed_conv_id_object_map}; for (int event_i = 0; event_i < 2; ++event_i) { std::map& cur_rem_msgs = *(rem_msgs[event_i]); @@ -590,7 +587,7 @@ void ShortMsgManager::storage_change_cb(msg_handle_t handle, PlatformResult ret(ErrorCode::NO_ERROR); for (int i = 0; i < pMsgIdList->nCount; ++i) { msg_struct_t msg; - ret = ShortMsgManager::getInstance().getMessage(pMsgIdList->msgIdList[i], &msg); + ret = short_msg_manager->getMessage(pMsgIdList->msgIdList[i], &msg); if (ret.IsError() || NULL == msg) { LoggerE("Failed to load short message"); delete eventSMS; @@ -632,7 +629,8 @@ void ShortMsgManager::storage_change_cb(msg_handle_t handle, } if (!eventSMS->items.empty() || !eventSMS->removed_conversations.empty()) { - PlatformResult ret = ShortMsgManager::callProperEventMessages(eventSMS, storageChangeType); + PlatformResult ret = + ShortMsgManager::callProperEventMessages(eventSMS, storageChangeType, short_msg_manager); // PlatformResult could be ignored here. eventSMS is deleted in callProperEventMessages() } else { LoggerD("No SMS messages, not triggering eventSMS"); @@ -640,7 +638,8 @@ void ShortMsgManager::storage_change_cb(msg_handle_t handle, eventSMS = NULL; } if (!eventMMS->items.empty() || !eventMMS->removed_conversations.empty()) { - PlatformResult ret = ShortMsgManager::callProperEventMessages(eventMMS, storageChangeType); + PlatformResult ret = + ShortMsgManager::callProperEventMessages(eventMMS, storageChangeType, short_msg_manager); // PlatformResult could be ignored here. eventMMS is deleted in callProperEventMessages() } else { LoggerD("No MMS messages, not triggering eventMMS"); @@ -653,10 +652,12 @@ void ShortMsgManager::registerStatusCallback(msg_handle_t msg_handle) { ScopeLogger(); m_msg_handle = msg_handle; // set message sent status callback - if (MSG_SUCCESS != msg_reg_sent_status_callback(m_msg_handle, &sent_status_cb, NULL)) { + if (MSG_SUCCESS != + msg_reg_sent_status_callback(m_msg_handle, &sent_status_cb, static_cast(this))) { LoggerE("sent status callback register error!!!"); } - if (MSG_SUCCESS != msg_reg_storage_change_callback(m_msg_handle, &storage_change_cb, NULL)) { + if (MSG_SUCCESS != + msg_reg_storage_change_callback(m_msg_handle, &storage_change_cb, static_cast(this))) { LoggerE("storage change callback register error!"); } } @@ -847,7 +848,7 @@ PlatformResult ShortMsgManager::getMessage(int msg_id, msg_struct_t* out_msg) { PlatformResult ShortMsgManager::getConversationsForMessages( MessagePtrVector messages, msg_storage_change_type_t storageChangeType, - ConversationPtrVector* result) { + ConversationPtrVector* result, ShortMsgManager* shortMsgManager) { ScopeLogger("messages.size()=%d storageChangeType=%d", messages.size(), storageChangeType); std::unordered_set unique_conv_ids; @@ -864,7 +865,7 @@ PlatformResult ShortMsgManager::getConversationsForMessages( unique_conv_ids.insert(conv_id); ConversationPtr conv; PlatformResult ret = MessageConversation::convertMsgConversationToObject( - conv_id, ShortMsgManager::getInstance().m_msg_handle, &conv); + conv_id, shortMsgManager->m_msg_handle, &conv); if (ret.IsError()) { LoggerD("Convert msg conversation to object failed (%s)", ret.message().c_str()); return ret; diff --git a/src/messaging/short_message_manager.h b/src/messaging/short_message_manager.h index 3af6142..6bfe440 100644 --- a/src/messaging/short_message_manager.h +++ b/src/messaging/short_message_manager.h @@ -40,7 +40,8 @@ class FindMsgCallbackUserData; class ShortMsgManager { public: - static ShortMsgManager& getInstance(); + ShortMsgManager(); + virtual ~ShortMsgManager(); common::PlatformResult sendMessage(MessageRecipientsCallbackData* callback); void sendStatusCallback(msg_struct_t sent_status); @@ -58,11 +59,6 @@ class ShortMsgManager { std::string getMessageStatus(int id); private: - ShortMsgManager(); - ShortMsgManager(const ShortMsgManager&); - void operator=(const ShortMsgManager&); - virtual ~ShortMsgManager(); - /** * Listener for msg storage changes. Calls callbacks from ChangeListenerContainer. * @param handle @@ -87,9 +83,10 @@ class ShortMsgManager { */ static common::PlatformResult getConversationsForMessages( MessagePtrVector messages, msg_storage_change_type_t storageChangeType, - ConversationPtrVector* result); - static common::PlatformResult callProperEventMessages( - EventMessages* event, msg_storage_change_type_t storageChangeType); + ConversationPtrVector* result, ShortMsgManager* shortMsgManager); + static common::PlatformResult callProperEventMessages(EventMessages* event, + msg_storage_change_type_t storageChangeType, + ShortMsgManager* shortMsgManager); typedef std::map SendReqMap; SendReqMap m_sendRequests; msg_handle_t m_msg_handle; -- 2.7.4 From dcbd9d3bea193cf4e0ea5f788b52c91141444dd0 Mon Sep 17 00:00:00 2001 From: Piotr Kosko Date: Wed, 22 Nov 2017 14:48:04 +0100 Subject: [PATCH 15/16] [version] 2.09 Change-Id: I53fba98b16652feeabc5285b0bfba978767c2350 Signed-off-by: Piotr Kosko --- packaging/webapi-plugins.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/webapi-plugins.spec b/packaging/webapi-plugins.spec index d085250..f61a60d 100644 --- a/packaging/webapi-plugins.spec +++ b/packaging/webapi-plugins.spec @@ -10,7 +10,7 @@ %define crosswalk_extensions_path %{_libdir}/%{crosswalk_extensions} Name: webapi-plugins -Version: 2.08 +Version: 2.09 Release: 0 License: Apache-2.0 and BSD-3-Clause and MIT Group: Development/Libraries -- 2.7.4 From 44c3bc9d989b1ff537b4b1247f4ef5864072047f Mon Sep 17 00:00:00 2001 From: Pawel Kaczmarczyk Date: Thu, 30 Nov 2017 15:03:33 +0100 Subject: [PATCH 16/16] [Messaging] Fix problem with adding drafts [Bug] Managers were created in wrong order. MessagingManager calls registerStatusCallback on ShortMsgManager, so ShortMsgManager has to be created before. [Verification] 100% passrate (with re-run) tct-messaging-email-tizen-tests tct-messaging-sms-tizen-tests tct-messaging-mms-tizen-tests change-Id: Ia4e4b1771f40e60a4f5ef4fcd6f3c5f420637546 Signed-off-by: Pawel Kaczmarczyk --- src/messaging/messaging_instance.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/messaging/messaging_instance.h b/src/messaging/messaging_instance.h index d5ff5d7..c3f11e0 100644 --- a/src/messaging/messaging_instance.h +++ b/src/messaging/messaging_instance.h @@ -58,9 +58,9 @@ class MessagingInstance : public common::ParsedInstance { void MessageStorageRemoveChangeListener(const picojson::value& args, picojson::object& out); void MessageGetMessageStatus(const picojson::value& args, picojson::object& out); - MessagingManager manager_; ShortMsgManager short_msg_manager_; EmailManager email_manager_; + MessagingManager manager_; PostQueue queue_; }; -- 2.7.4